打字稿:使用注入参数隐式调用构造函数

typescript: invoke constructor with injected parameters implicity

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

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

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

1.) 你需要

  • 将@Injectable() 添加到 GsPoint 并且

  • 像提供者一样提供 GsPoint:[GsPoint] 在组件或 NgModule 中。

当您随后在某处注入 GsPoint 时,一个 KeyValueDiffers 实例在由 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);

}

这样 myDiffer 将是一个 KeyValueDiffers 实例,由 Angulars DI 实例化,并且 myDiffer 将在实例化时注入到 GSPoint

但是,如果您想以这种方式进行操作,那么在您使用此 class 的组件或服务中,您必须传递 KeyValueDiffers 服务的 this.myDiffer 实例。 (注意:- KeyValueDiffers 必须注入到您创建此 GsPoint Class 对象的组件中)

 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
   }   

}

您描述的是某种服务定位器。 通常我不建议使用这种方法,因为你向调用者隐藏了 class 依赖关系,并可能使测试变得更加困难。