Angular2中带有可选参数的依赖注入 [英] Dependency injection with optional parameter in Angular2

查看:217
本文介绍了Angular2中带有可选参数的依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个组件,它们需要相同的依赖关系,而该依赖关系需要为构造函数使用字符串.如何告诉angular2将特定类型的实例用于DI?

I have multiple components which require the same dependency which requires a string for the constructor. How can I tell angular2 to use a specific instance of the type for DI?

例如:

ChatUsers.ts:

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;
    }
}

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

If run this code, the error is:

无法解析User(?)的所有参数.确保他们都有 有效的类型或注释.

Cannot resolve all parameters for User(?). Make sure they all have valid type or annotations.

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

I'm using the most recent angular2 version: 2.0.0-alpha.44

推荐答案

要使依赖项为可选,只需使用这个矮子):

To make dependency optional just use @Optional parameter decorator (see this plunker):

class User {
  name: string;
  constructor(@Optional() name: string) {
    this.name = name;
  }
}

如果要将name注入到User中,则有两种解决方案:

If you want to inject name into User you have two solutions:

  1. 向应用程序提供商中添加一些'userName'提供商,并使用此导航键).
  1. Add some 'userName' provider to app providers and use @Inject('userName') parameter decorator to inject it into User (see this plunker).

class User {
  name: string;
  constructor(@Inject('userName') name: string) {
      this.name = name;
  }
}
// ...
bootstrap(ChatApp, [
  User, 
  provide('userName', { useValue: 'Bob'})
]);

  1. 使用 useFactory 来专门实例化您的用户(请参见此插件):

bootstrap(ChatApp, [
  provide(User, { useFactory: () => new User('John') })
]);

这篇关于Angular2中带有可选参数的依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆