简体   繁体   English

使用提供程序向我的服务构造函数注入多个值-angular2

[英]inject multiple values using provider to my service constructor - angular2

How can inject multiple values to my service if I have constructor like this 如果我有这样的构造函数,如何向我的服务注入多个值

@Injectable()
export class MyService implements OnInit {
    constructor(private http: Http, @Inject('name') @Optional() public name?: string) {            
}

and inside AppModule I tried following 在AppModule中,我尝试了以下

...
providers: [
    SecurityService, providers:[
      {  provide: 'username', useValue: ''  },
      {  provide: 'http', useValue: Http  }
    ],
..

but I'm getting syntax error in line SecurityService, providers:[ 但我在SecurityService, providers:[行中遇到语法错误SecurityService, providers:[

Cannot find name providers

Just pass in the dependencies as an array (you don't need to destructure it): 只需将依赖项作为数组传递(您无需对其进行解构):

...
providers: [
    SecurityService, 
    [
      {  provide: 'username', useValue: ''  },
      {  provide: 'http', useValue: Http  }
    ],
...

Or go ahead and destructure it for the sake of cleaner code: 或者,为了更简洁的代码而对其进行重构:

...
providers: [
    SecurityService, 
    {  provide: 'username', useValue: ''  },
    {  provide: 'http', useValue: Http  }
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM