Angular 4: When and why is @Inject is used in constructor?

后端 未结 3 820
孤街浪徒
孤街浪徒 2021-02-01 16:53

Problem Statment

I am learning Angular 4 and I have stumble upon a code where @Inject is being used in a constructor and I am

3条回答
  •  眼角桃花
    2021-02-01 17:34

    @Inject() is a manual mechanism for letting Angular know that a parameter must be injected.

    import { Component, Inject } from '@angular/core';
    import { ChatWidget } from '../components/chat-widget';
    
    @Component({
      selector: 'app-root',
      template: `Encryption: {{ encryption }}`
    })
    export class AppComponent {
      encryption = this.chatWidget.chatSocket.encryption;
    
      constructor(@Inject(ChatWidget) private chatWidget) { }
    }
    

    In the above we've asked for chatWidget to be the singleton Angular associates with the class symbol ChatWidget by calling @Inject(ChatWidget). It's important to note that we're using ChatWidget for its typings and as a reference to its singleton. We are not using ChatWidget to instantiate anything, Angular does that for us behind the scenes

    From https://angular-2-training-book.rangle.io/handout/di/angular2/inject_and_injectable.html

提交回复
热议问题