Angular @Inject 注解的实际应用例子和工作原理浅析
2023-09-14 09:03:59 时间
看一个实际的例子:
import { Component, Inject } from '@angular/core';
import { Http } from '@angular/http';
@Component({
selector: 'example-component',
template: '<div>I am a component</div>'
})
class ExampleComponent {
constructor(@Inject(Http) private http) {
// use `this.http` which is the Http provider
}
}
此时,@Inject 是指定此查找标记的手动方式,后跟小写的 http 参数告诉 Angular 分配它的对象。
当组件或服务需要大量依赖项时,这可能(并且将会)变得非常混乱。 由于 Angular 支持从发出的元数据中解析依赖关系,因此大多数时候不需要使用 @Inject。
我们唯一需要使用 @Inject 的地方是像 OpaqueToken 这样的场景——它创建一个唯一的空白令牌,用作依赖注入提供程序。
我们使用@Inject 的原因是因为我们不能使用 OpaqueToken 作为参数的类型,例如下面的代码将不会工作:
const myToken = new OpaqueToken('myValue');
@Component(...)
class ExampleComponent {
constructor(private token: myToken) {}
}
在这里,myToken 不是类型,它是一个值——这意味着 TypeScript 无法编译它。 但是,当我们将 @Inject 与 OpaqueToken 一起引入时,整个依赖注入会重新开始工作:
const myToken = new OpaqueToken('myValue');
@Component(...)
class ExampleComponent {
constructor(@Inject(myToken) private token) {
// use the provider for `token`
}
}
上面提供了一个使用 @Inject 手动指定要注入的令牌的示例,并显示该令牌可以是任何值。 这意味着在 Angular 依赖注入的场景里,我们并不限于 TypeScript 归类为“类型”的内容。
再看另一个例子:
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) { }
}
在上面我们通过调用 @Inject(ChatWidget)
要求chatWidget 成为Angular 与类符号ChatWidget 相关联的单例。 重要的是要注意,我们使用 ChatWidget 进行类型化并作为对其单例的引用。 我们没有使用 ChatWidget 来实例化任何东西,Angular 在幕后为我们做这件事。
使用 TypeScript 时,@Inject
仅用于注入原语(primitives)
。 TypeScript 的类型让 Angular 在大多数情况下知道该做什么。 上面的示例将在 TypeScript 中简化为:
import { Component } from '@angular/core';
import { ChatWidget } from '../components/chat-widget';
@Component({
selector: 'app',
template: `Encryption: {{ encryption }}`
})
export class App {
encryption = this.chatWidget.chatSocket.encryption;
constructor(private chatWidget: ChatWidget) { }
}
相关文章
- [Unit Testing Angular] RxJS Marble testing for Component
- [Angular] Router outlet events
- [Angular] Using the platform agnostic Renderer & ElementRef
- [Angular 2] Factory Provider with dependencies
- [AngularJS] angular-formly: Extending Types
- [AngularJS] Angular 1.3 ngMessages with ngAnimate
- Angular组件生命周期钩子
- [Angular] Run Angular CLI with https
- [Angular] Show a Loading Indicator for Lazy Routes in Angular
- [Angular + TsLint] Disable directive selector tslint error
- Angular Universal 应用避免 SSR hang 的一些指导方针
- Angular 项目里 angular.json 文件内容的学习笔记
- 如何处理 Angular 单页面应用里的 a 标签,避免点击后重新加载整个应用
- Angular ctorParameters,decorator等元数据,包含在ActivatedRouteSnapshot数据结构里
- 关于 Angular SSR 应用在渲染中止时如何避免内存泄漏问题的一些尝试
- Angular应用的angular.json文件字段一览
- Angular应用里child Component如何向parent Component发送事件
- Angular应用内路由(In App Route)的最佳实践
- Angular 应用的Support package
- 理论+案例,带你掌握Angular依赖注入模式的应用