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

Vikas Bansal picture Vikas Bansal · Nov 1, 2017 · Viewed 17.6k times · Source

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 not able to figure out why...

Code and Source

I am using Angular 4 Material

Code Source: https://material.angular.io/components/dialog/overview

In the code, they are injecting MAT_DIALOG_DATA

constructor(public dialogRef: MatDialogRef<DialogOverviewExampleDialog>,
             @Inject(MAT_DIALOG_DATA) public data: any
           ) { }

Can anyone please elaborate what does it mean and when/where should we do this?

Answer

Rahul Singh picture Rahul Singh · Nov 1, 2017

@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