加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 18:00:54 所属栏目:安全 来源:网络整理
导读:我有多个组件需要相同的依赖项,这需要构造函数的字符串.如何告诉angular2使用DI的特定类型实例? 例如: ChatUsers.ts: @Component({ selector: "chat-users"})@View({ directives: [],templateUrl: '/js/components/ChatUsers.html'})export class ChatUse
我有多个组件需要相同的依赖项,这需要构造函数的字符串.如何告诉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') })
]);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读