使用Angular2中的可选参数进行依赖注入

Ste*_*ter 4 typescript angular

我有多个组件需要相同的依赖项,这需要构造函数的字符串.如何告诉angular2使用DI的特定类型实例?

例如:

ChatUsers.ts:

@Component({
    selector: "chat-users"
})
@View({
    directives: [],
    templateUrl: '/js/components/ChatUsers.html'
})
export class ChatUsers {

    constructor(public currentUser : User) {
    }
}
Run Code Online (Sandbox Code Playgroud)

和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 ]);
Run Code Online (Sandbox Code Playgroud)

User.ts

export class User {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果运行此代码,则错误为:

无法解析用户的所有参数(?).确保它们都具有有效的类型或注释.

我正在使用最新的angular2版本: 2.0.0-alpha.44

ale*_*ods 17

要使依赖项可选,只需使用@Optional参数装饰器(请参阅此plunker):

class User {
  name: string;
  constructor(@Optional() name: string) {
    this.name = name;
  }
}
Run Code Online (Sandbox Code Playgroud)

如果要注入nameUser你有两种解决方案:

  1. 将一些'userName'提供程序添加到应用程序提供程序并使用@Inject('userName')参数装饰器将其注入User(请参阅此plunker).
class User {
  name: string;
  constructor(@Inject('userName') name: string) {
      this.name = name;
  }
}
// ...
bootstrap(ChatApp, [
  User, 
  provide('userName', { useValue: 'Bob'})
]);
Run Code Online (Sandbox Code Playgroud)
  1. 使用useFactory具体实例用户(请参阅此plunker):
bootstrap(ChatApp, [
  provide(User, { useFactory: () => new User('John') })
]);
Run Code Online (Sandbox Code Playgroud)

  • @Best_Where_Gives你应该在使用之前导入`@ Optional`.从'angular/core'`尝试`import {Optional}.查看文档[here](https://angular.io/api/core/Optional) (2认同)