12

我不明白何时使用 @Inject 以及何时使用 @Injectable ?

  import {Component, Inject, provide} from '@angular/core';
    import {Hamburger} from '../services/hamburger'; 
    export class App {
       bunType: string;
       constructor(@Inject(Hamburger) h) {
         this.bunType = h.bun.type;
       }
     }

和..

  import {Injectable} from '@angular/core';
    import {Bun} from './bun';
    @Injectable()
    export class Hamburger {
      constructor(public bun: Bun) {
      }
    }
4

2 回答 2

13

@Injectable装饰器旨在实际设置一些有关将哪些依赖项注入关联类的构造函数的元数据。这是一个不需要参数的类装饰器。没有这个装饰器,就不会注入依赖...

@Injectable()
export class SomeService {
  constructor(private http:Http) {
  }
}

@Inject装饰器必须在构造函数参数级别使用,以指定有关要注入的元素的元数据。没有它,使用参数的类型(obj:SomeType等价于@Inject(SomeType) obj)。

@Injectable()
export class SomeService {
  constructor(@Inject(Http) private http:Http, @Inject('sometoken') obj) {
  }
}
于 2016-05-19T06:24:51.380 回答
6

您必须阅读此区别-@Inject 和 @Injectable

@注入()

是一种手动机制,用于让 Angular 知道必须注入参数。

When using TypeScript, @Inject is only needed for injecting primitives. For eg:

export class AppComponent {
  encryption = this.chatWidget.chatSocket.encryption;

  constructor(@Inject(ChatWidget) private chatWidget) { }
}

@Injectable()

lets Angular know that a class can be used with the dependency injector.

For eg:

@Injectable()
export class ChatWidget {
constructor(
    public authService: AuthService,
    public authWidget: AuthWidget,
    public chatSocket: ChatSocket) { }
}

In the above example Angular's injector determines what to inject into ChatWidget's constructor by using type information

于 2018-07-23T11:49:27.143 回答