Angular 通过依赖注入机制注入一个对象的例子,什么是 ElementInjector
假設(shè)我在app.config.ts里定義了一個(gè)interface AppConfig和一個(gè)對(duì)象HERO_DI_CONFIG, 我想將后者注入到一個(gè)類(lèi)的構(gòu)造函數(shù)里去:
export interface AppConfig {apiEndpoint: string;title: string;}import { InjectionToken } from '@angular/core';export const APP_CONFIG = new InjectionToken<AppConfig>('app.config');export const HERO_DI_CONFIG: AppConfig = {apiEndpoint: 'api.heroes.com',title: 'Dependency Injection' };使用InjectionToken新建一個(gè)token,類(lèi)型參數(shù)為AppConfig,單引號(hào)里的app.config是injection token的描述信息。
在NgModule里使用useValue注入:
在需要使用這個(gè)依賴(lài)的地方,將token APP_CONFIG傳入@Inject:
最后的效果:
在控制反轉(zhuǎn)中,”控制“是指對(duì)程序流程的控制,”反轉(zhuǎn)“則是將控制權(quán)從程序員的手里反轉(zhuǎn)到了外層框架。
@optional修飾符
@Component({selector: 'app-notification',templateUrl: './notification.component.html',styleUrls: ['./notification.component.less'] }) export class NotificationComponent implements OnInit {constructor(@Optional() private msg: MessageService) {}ngOnInit() {this.msg.send();} }如果無(wú)法注入,msg被Angular解析成null,而不會(huì)拋出錯(cuò)誤。
@Optional() 允許 Angular 將您注入的服務(wù)視為可選服務(wù)。這樣,如果無(wú)法在運(yùn)行時(shí)解析它,Angular 只會(huì)將服務(wù)解析為 null,而不會(huì)拋出錯(cuò)誤
@Self
使用 @Self 讓 Angular 僅查看當(dāng)前組件或指令的 ElementInjector
@SkipSelf
使用 @SkipSelf(),Angular 在父 ElementInjector 中而不是當(dāng)前 ElementInjector 中開(kāi)始搜索服務(wù)
一個(gè)例子:在父組件中定義了一個(gè)服務(wù):ParentMessageService
import { Injectable } from '@angular/core';@Injectable({providedIn: 'root' }) export class ParentMessageService {constructor() {}send() {console.log('come from parent');} }@Component({selector: 'app-container',templateUrl: './container.component.html',styleUrls: ['./container.component.less'],providers: [{ provide: MessageService, useClass: ParentMessageService }] }) export class ContainerComponent implements OnInit {constructor() {}ngOnInit() {} }子組件中,我們已提供了服務(wù),但是注入時(shí)使用了 @SkipSelf() 修飾符
@Component({selector: 'app-notification',templateUrl: './notification.component.html',styleUrls: ['./notification.component.less'],providers: [{provide: MessageService,useClass: NewMessageService}] }) export class NotificationComponent implements OnInit {constructor(@SkipSelf() private msg: MessageService) {}ngOnInit() {this.msg.send();} }最終,Angular會(huì)注入父組件的服務(wù)實(shí)例:ParentMessageService
什么是 Angular 的 ElementInjector?
這個(gè)概念和 Angular 多級(jí)注入器有關(guān)。Angular creates ElementInjectors implicitly for each DOM element. Angular 會(huì)為每個(gè) DOM 元素隱式創(chuàng)建 ElementInjector。
Providing a service in the @Component() decorator using its providers or viewProviders property configures an ElementInjector.
當(dāng)我們?cè)?Component 里定義 providers 時(shí),我們就已經(jīng)配置了一個(gè) ElementInjector.
@Component({...providers: [{ provide: ItemService, useValue: { name: 'lamp' } }] }) export class TestComponentWhen you provide services in a component, that service is available via the ElementInjector at that component instance.
通過(guò) ElementInjector,我們配置在 Component 里的服務(wù),能夠被組件實(shí)例使用到。
組件是一種特殊類(lèi)型的指令,這意味著 @Directive() 具有 providers 屬性,@Component() 也同樣如此。 這意味著指令和組件都可以使用 providers 屬性來(lái)配置提供者。當(dāng)使用 providers 屬性為組件或指令配置提供者時(shí),該提供程商就屬于該組件或指令的 ElementInjector。同一元素上的組件和指令共享同一個(gè)注入器。
要獲取更多Jerry的原創(chuàng)文章,請(qǐng)關(guān)注公眾號(hào)"汪子熙":
總結(jié)
以上是生活随笔為你收集整理的Angular 通过依赖注入机制注入一个对象的例子,什么是 ElementInjector的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 微信运动怎么看自己走了几步 微信运动步数
- 下一篇: 是否能梦到电子羊是什么梗