使用参数化构造函数的依赖注入

时间:2018-01-26 07:32:06

标签: angular

我正在处理角度2中的依赖注入。 我写了一个不包含任何构造函数的示例服务 我的服务:

import {Injectable} from '@angular/core'

@Injectable()
export class MyFirstServiceClass{
  //Not working with parameter
  // constructor(nm:string){   
  // }
  SayHello(){
    alert();
      return "Hello, I'm Service...";
  }
}

我通过构造函数中的依赖注入访问了服务,如下所示:

import { Component } from '@angular/core';
import {MyFirstServiceClass} from './MyFirstService.service'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  Assignonclick : string;
  constructor(public refsrvc : MyFirstServiceClass){
   this.title = refsrvc.SayHello();
  }
 CallServiceOnBtnClick(){
  this.Assignonclick = this.refsrvc.SayHello();
 }

}

如果我没有为我的服务类的构造函数提供参数,那么它是有效的。 如果我执行以下操作就像在构造函数中提供参数一样,我无法执行DI。

@Injectable()
export class MyFirstServiceClass{
  //Not working with parameter
  constructor(nm:string){   
  }
  SayHello(){
    alert();
      return "Hello, I'm Service...";
  }
}

这为我提供了以下图片直接错误:

enter image description here 如何使用参数执行DI?

3 个答案:

答案 0 :(得分:2)

因为您希望DI机制为您创建scaleToFill的实例 - DI机制必须知道有关该可注入服务的构造函数参数的任何信息。

当你这样做时

MyFirstServiceClass

DI知道有类型constructor(public refsrvc : MyFirstServiceClass){ } 注入的东西,所以它会尝试注入它。但是当它尝试访问该类的构造函数时 - 在那一刻,DI对参数MyFirstServiceClass一无所知,所以为什么它不能创建nm:string的实例。因此,根据您的参数类型MyFirstServiceClass,它会为您提供正确的错误

  

没有字符串提供者

答案 1 :(得分:0)

您的服务:

@Injectable()
export class MyFirstServiceClass{
  nm: string;

  constructor(nm:string){
    this.nm = nm;
  }
  SayHello(){
    alert();
      return "Hello, I'm Service...";
  }
}

当您想要使用它时:

import { Component } from '@angular/core';
import {MyFirstServiceClass} from './MyFirstService.service'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  refsrvc : MyFirstServiceClass
  Assignonclick : string;

  constructor() {
    this.refsrvc = new MyFirstServiceClass('The string of the constructor');
    this.title = this.refsrvc.SayHello();
  }

  CallServiceOnBtnClick(){
    this.Assignonclick = this.refsrvc.SayHello();
  }
}

答案 2 :(得分:0)

如果在服务的构造函数类中定义了参数,则需要传递参数或使用get / set。