typescript:使用注入参数隐式调用构造函数

typescript:使用注入参数隐式调用构造函数,typescript,dependency-injection,constructor,angular5,Typescript,Dependency Injection,Constructor,Angular5,如何以这种方式创建点的实例: let npoint = new Point(); Point的构造函数需要一个参数(不同),该参数应该被注入 import { DoCheck, KeyValueDiffers, KeyValueDiffer } from '@angular/core'; export class GsPoint { uuid: string; differ: any; constructor(private differs: KeyValueDiffers)

如何以这种方式创建点的实例:

let npoint = new Point();
Point的构造函数需要一个参数(不同),该参数应该被注入

import { DoCheck, KeyValueDiffers, KeyValueDiffer } from '@angular/core';

export class GsPoint {

  uuid: string;

  differ: any;
  constructor(private differs: KeyValueDiffers) {
    this.differ = this.differs.find({}).create();
  }

  ngDoCheck() {
    const change = this.differ.diff(this);
    if (change) {
      change.forEachChangedItem(item => {
        console.log('item changed', item);
      });
    }
  }
}

如果它是一个普通类(不是组件或指令),那么您不能像我们在组件级别或模块级别那样注入
keyvaluedifferents
服务

1)你需要

  • 将@Injectable()添加到GsPoint并

  • 在组件或模块中提供类似GsPoint的提供程序:[GsPoint]

然后,当您将GsPoint注入某处时,keyValueDifferences实例在被DI实例化时(在第一次注入之前)会被传递到GsPoint

2.)另一种方法是配置自定义喷油器,如

constructor(private injector:Injector) { 
   let resolvedProviders = ReflectiveInjector.resolve([KeyValueDiffers]);
   let childInjector = ReflectiveInjector.fromResolvedProviders(resolvedProviders,this.injector);

  let myDiffer : KeyValueDiffers= childInjector.get(KeyValueDiffers);
}

这样,
mydifferent
将是一个由Angulars DI实例化的
KeyValueDifferences
实例,并且当实例化时,
mydifference
将被注入到
GSPoint

但是,如果您希望以这种方式执行此操作,那么在组件或服务中,无论您在哪里使用此类,都必须传递
this.mydifferent
keyvaluedifferences
实例。(注意:-
keyvaluedifferences
必须注入到创建此GsPoint类对象的组件中)


}

您描述的是某种服务定位器。 一般来说,我不建议使用这种方法,因为您对调用方隐藏了类依赖项,这可能会使测试更加困难

 import {KeyValueDiffers , Component  } from '@angular/core';
 import {GSPoint} from '../gspoint/gspoint.ts';

 @Component({
    'selector': 'app-sample',
    'templateUrl':'sample.html',
    'styleUrl': 'sample.css'   
  })
 export class Sample {

   constructor(private diff: KeyValueDiffers){

     }
 ngOnInit(){
     let gsPoint = new GSPoint(this.dff); // this is how you can create object
   }