通过Injector动态传递数据

374 阅读1分钟

动态创建组件时,@Input,和Output略显不便!可通过Injector动态传递数据,更加灵活方便! 体会angular依赖注入带来的便捷!

import { Injector } from '@angular/core';
export class CustomInjector implements Injector {
    constructor(
        private _parentInjector: Injector,
        // 自定义注入
        private _customTokens: WeakMap<any, any>
    ) { }
    get(token: any, notFoundValue?: any): any {
        const value = this._customTokens.get(token);
        if (typeof value !== 'undefined') {
            return value;
        }
        return this._parentInjector.get<any>(token, notFoundValue);
    }
}

新建一个injector, 动态创建Component

attachMenuComponent(comp: Type<any>, data: any): ComponentRef<any> {
    const injectionTokens = new WeakMap<any,any>([CustomData,data])
    const injector = new CustomInjector(this._injector, injectionTokens);

    const factory = this.factory.resolveComponentFactory(comp);
    return this.menuView.createComponent(factory,null, injector);
}
  • 使用时
export class Dialog {
    constructor(@Inject(CustomData) data: any){
        // 这个里即拿到data数据
    }
}