What is the difference between @Inject and @Injectable in Angular 2 typescript

后端 未结 2 1769
清酒与你
清酒与你 2021-01-02 03:10

I don\'t understand When to use @Inject and when to use @Injectable ?

  import {Component, Inject, provide} from \'@angular/core\';
    import {Hamburger} fr         


        
2条回答
  •  独厮守ぢ
    2021-01-02 03:30

    You must read this difference- @Inject and @Injectable

    @Inject()

    is a manual mechanism for letting Angular know that a parameter must be injected.

    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

提交回复
热议问题