我有多个组件需要相同的依赖项,这需要构造函数的字符串.如何告诉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; } }
Cannot resolve all parameters for User(?). Make sure they all have
valid type or annotations.
我正在使用最新的angular2版本:2.0.0-alpha.44
解决方法
要使依赖项可选,只需使用
@Optional
参数装饰器(参见
this plunker):
class User { name: string; constructor(@Optional() name: string) { this.name = name; } }
>向应用提供商添加一些’userName’提供商,并使用@Inject('userName')
参数装饰器将其注入用户(参见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') }) ]);