角4:在构造函数中何时使用@Inject以及为什么使用@Inject? [英] Angular 4: When and why is @Inject is used in constructor?
问题描述
问题陈述
我正在学习Angular 4,我偶然发现了在constructor
中使用@Inject
的代码,但我不知道为什么...
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...
代码和来源
我正在使用Angular 4材质
I am using Angular 4 Material
代码源: https://material.angular.io/组件/对话框/概述
在代码中,他们正在注入MAT_DIALOG_DATA
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?
推荐答案
@Inject()
是一种手动机制,用于让Angular知道 必须输入参数.
@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) { }
}
在上面,我们要求chatWidget
是单例Angular
通过调用与class
符号ChatWidget
关联
@Inject(ChatWidget)
.请务必注意,我们正在使用
ChatWidget
键入和作为对其单例的引用.
我们不是使用ChatWidget
实例化任何东西,Angular确实
为我们幕后的人
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
来自 https://angular-2-training -book.rangle.io/handout/di/angular2/inject_and_injectable.html
这篇关于角4:在构造函数中何时使用@Inject以及为什么使用@Inject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!