角4:在构造函数中何时使用@Inject以及为什么使用@Inject? [英] Angular 4: When and why is @Inject is used in constructor?

查看:212
本文介绍了角4:在构造函数中何时使用@Inject以及为什么使用@Inject?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题陈述

我正在学习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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆