@Inject 真的只在不使用 TS 或 emitDecoratorMetadata:false 转译的情况下才需要吗

Is @Inject really only needed for the cases when not transpiling with TS or emitDecoratorMetadata:false

我正在阅读 @Injectable@Inject 上的 this article,其中包含以下内容:

Problem solved. In fact, this is exactly what @Inject is for when not transpiling with TypeScript. If we take a look at the transpiled code now, we see that all the needed metadata is generated (yeap simplified).

...

We can basically put any decorator on our code, as long as it’s either attached to the class declaration, or to the constructor parameter. In other words, we could remove @Inject again and use something else that we put on the class, because that will cause TypeScript to emit metadata for the constructor parameters too... Luckily, Angular comes with yet another decorator we can use. @Injectable is normally used for Dart metadata generation. It doesn’t have any special meaning in TypeScript-land, however, it turns out to be a perfect fit for our use case.

那么,我的理解是否正确,即:

  1. 如果 class 被用作其他 classes 的可注入对象但不依赖于任何其他 class,它既不需要 @Injectable 也不需要 @Inject构造函数
  2. 如果 class 依赖于任何其他 class 并且没有使用任何装饰器,则它需要 @Injectable() 个装饰器
  3. 如果TS和emitDecoratorMetadata:true一起使用,@Inject装饰器是没有用的
  4. 如果不使用 TS,或与 emitDecoratorMetadata:false 一起使用,@Inject 是指定依赖关系的唯一机制
  1. 是的,AFAIK("dependent on any other class" 见下文,除了 类 之外还有其他类型的依赖关系)

  2. 是的,但据我所知,最好使用 @Injectable()

  3. @Inject() 当参数类型与所提供的注册类型不匹配时需要。

providers: [
  MyService,
  {provide 'myservice', useClass: MyService},
  {provide myserviceOpaqueToken, useClass: MyService},
]
constructor(private myService:MyService) {} // no @Inject() required
constructor(@Inject('myservice') private myService:MyService) {} //  @Inject() used to lookup the provider by string name
constructor(@Inject(myserviceOpaqueToken) private myService:MyService) {} //  @Inject() used to lookup the provider by OpaqueToken

这也暴露了您在其他陈述中的一些误解。 类 可以依赖于其他参数而不是其他 类

providers: [
  {provide 'myconfigvalue', useValue: '42'},
]

constructor(@Inject('myconfigvalue') private myConfigValue:string) {}   
  1. 还有static get parameters() { ... }getter来指定依赖关系。我想这对于将 Angular2 与 ES5/6 一起使用仍然有效(我自己从未使用过)

https://medium.com/@blacksonic86/angular-2-dependency-injection-in-es6-f5551a3d6bf#.kgxjvcinv

@Component({
  selector: 'app',
  template: `
    <ul>
      <li *ngFor="#city of getCities()">{{ city }}</li>
    </ul>
  `
})
class AppComponent {
  static get parameters() {
    return [[CityService]];
  }

  constructor(cityService) {
    this._cityService = cityService;
  }

  getCities() {
    return this._cityService.getCities();
  }
}