问题描述
问题陈述
我正在学习 Angular 4,我偶然发现了一个代码,其中 @Inject
被用于 constructor
并且我无法弄清楚为什么......
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
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?
推荐答案
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
这篇关于Angular 4:何时以及为什么在构造函数中使用@Inject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!