我有多个组件需要相同的依赖项,这需要构造函数的字符串。如何告诉angular2使用DI的类型的特定实例?
例如:
ChatUsers.ts:
@Component({
selector: "chat-users"
})
@View({
directives: [],
templateUrl: '/js/components/ChatUsers.html'
})
export class ChatUsers {
constructor(public currentUser : User) {
}
}
和app.ts:
/// <reference path="../libs/typings/tsd.d.ts" />
import {Component, View, bootstrap} from 'angular2/angular2';
import {User} from "User";
// How to create a user, e.g. new User('John') and use it for DI?
@Component({
selector: 'chat-app'
})
@View({
directives: [ ],
template: `
<div> Some text
</div>`
})
class ChatApp {
constructor(public user: User) {
// do something with user
}
}
bootstrap(ChatApp, [ User ]);
User.ts
export class User {
name: string;
constructor(name: string) {
this.name = name;
}
}
如果运行此代码,则错误为:
无法解析用户(?)的所有参数。确保他们都有 有效的类型或注释。
我使用的是最新的angular2版本:2.0.0-alpha.44
答案 0 :(得分:17)
要使依赖项可选,只需使用@Optional
参数装饰器(参见this plunker):
class User {
name: string;
constructor(@Optional() name: string) {
this.name = name;
}
}
如果您想将name
注入User
,您有两个解决方案:
'userName'
提供商,并使用@Inject('userName')
参数装饰器将其注入User
(请参阅this plunker)。class User {
name: string;
constructor(@Inject('userName') name: string) {
this.name = name;
}
}
// ...
bootstrap(ChatApp, [
User,
provide('userName', { useValue: 'Bob'})
]);
useFactory
专门实例化您的用户(请参阅this plunker):bootstrap(ChatApp, [
provide(User, { useFactory: () => new User('John') })
]);