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

时间:2016-05-19 06:22:12

标签: dependency-injection typescript angular injectable

我不明白何时使用@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) {
      }
    }

2 个答案:

答案 0 :(得分:6)

@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) {
  }
}

答案 1 :(得分:1)

您必须阅读此差异-@Inject and @Injectable

@Inject()

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

使用TypeScript时,仅@Inject才需要注入基元。 例如:

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

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

@Injectable()

让Angular知道可以将类与依赖项一起使用     喷射器。

例如:

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

在上面的示例中,Angular的注入器通过使用类型信息确定向ChatWidget的构造器注入什么