Angular 2打字稿中的@Inject和@Injectable有什么区别

Sar*_*dav 9 dependency-injection injectable typescript angular

我不明白何时使用@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;
       }
     }
Run Code Online (Sandbox Code Playgroud)

和..

  import {Injectable} from '@angular/core';
    import {Bun} from './bun';
    @Injectable()
    export class Hamburger {
      constructor(public bun: Bun) {
      }
    }
Run Code Online (Sandbox Code Playgroud)

Thi*_*ier 7

@Injectable装饰的目的是实际设置哪些依赖关系注入到相关类的构造一些元数据.它是一个不需要参数的类装饰器.如果没有这个装饰器,就不会注入依赖...

@Injectable()
export class SomeService {
  constructor(private http:Http) {
  }
}
Run Code Online (Sandbox Code Playgroud)

所述@Inject装饰必须在构造参数的级别被用于指定关于元素注入元数据.没有它,使用参数类型(obj:SomeType相当于@Inject(SomeType) obj).

@Injectable()
export class SomeService {
  constructor(@Inject(Http) private http:Http, @Inject('sometoken') obj) {
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢@Thierry,但是你能解释一下为什么我们使用 @Injectable() 我们可以直接导出类,那么为什么我们使用 @Injectable() ? (2认同)

inf*_*kit 6

你必须阅读这个区别 - @Inject 和 @Injectable

@注入()

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

使用 TypeScript 时,@Inject 仅用于注入原语。例如:

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

  constructor(@Inject(ChatWidget) private chatWidget) { }
}
Run Code Online (Sandbox Code Playgroud)

@Injectable()

让 Angular 知道一个类可以与依赖注入器一起使用。

例如:

@Injectable()
export class ChatWidget {
constructor(
    public authService: AuthService,
    public authWidget: AuthWidget,
    public chatSocket: ChatSocket) { }
}
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,Angular 的注入器通过使用类型信息来确定将什么注入到 ChatWidget 的构造函数中