[英]Angular: understanding how DI works in dynamicaly loaded component
我遇到注入到动态加载的组件的服务的奇怪行为。 考虑以下服务
@Injectable({
providedIn: 'root'
})
export class SomeService {
private random = Math.random() * 100;
constructor() {
console.log('random', this.random);
}
}
该服务被添加为两个组件的依赖项。 第一个组件是延迟加载模块的一部分。 而第二个是动态加载的。 以下服务加载具有动态组件的模块
export const COMPONENT_LIST = new InjectionToken<any>('COMPONENT_LIST');
export const COMPONENT_TYPE = new InjectionToken<any>('COMPONENT_TYPE');
@Injectable({
providedIn: 'root'
})
export class LoaderService {
constructor(
private injector: Injector,
private compiler: Compiler,
) { }
getFactory<T>(componentId: string): Observable<ComponentFactory<T>> {
// COMPONENT_LIST is passed through forRoot() from the module that declares first component
const componentList = this.injector.get(COMPONENT_LIST);
const m = componentList.find(m => m.componentId === componentId);
const promise: Promise<ComponentFactory<T>> = (!m) ? null :
m.loadChildren
.then((mod: any) => {
return this.compiler.compileModuleAsync(mod);
})
.then((mf: NgModuleFactory<any>) => {
const mr: NgModuleRef<any> = mf.create(this.injector);
const type: Type<T> = mr.injector.get<Type<T>>(COMPONENT_TYPE); // DYNAMIC_COMPONENT is provided in loaded module
return mr.componentFactoryResolver.resolveComponentFactory<T>(dynamicComponentType);
});
return from(promise);
}
}
在同一个模块中,我声明了以下组件(以放置动态加载的组件)和指令
@Component({
selector: 'dynamic-wrapper',
template: `<ng-container dynamicItem></ng-container>`
})
export class DynamicWrapperComponent implements AfterViewInit, OnDestroy {
@Input() itemId: string;
@Input() inputParameters: any;
@ViewChild(DynamicItemDirective)
private dynamicItem: DynamicItemDirective;
private unsubscribe$: Subject<void> = new Subject();
constructor(
private loaderService: LoaderService
) { }
ngAfterViewInit(): void {
this.loaderService.getComponentFactory(this.itemId).subscribe((cf: ComponentFactory<any>) => {
this.dynamicItem.addComponent(cf, this.inputParameters);
});
}
}
...
@Directive({
selector: '[dynamicItem]'
})
export class DynamicItemDirective {
constructor(protected viewContainerRef: ViewContainerRef) { }
public addComponent(cf: ComponentFactory<any>, inputs: any): void {
this.viewContainerRef.clear();
const componentRef: ComponentRef<any> = this.viewContainerRef.createComponent(cf);
Object.assign(componentRef.instance, inputs);
// if I do not call detectChanges, ngOnInit in loaded component will not fire up
componentRef.changeDetectorRef.detectChanges();
}
}
SomeService
定义在一个单独的模块中,该模块在具有第一个组件的延迟加载模块和动态加载模块中都导入。
在两个组件都初始化后,我看到console.log('random', this.random)
在控制台中有两个不同的数字,尽管在装饰器中providedIn: 'root'
。 这种奇怪行为的原因是什么?
延迟加载的模块不会像预期的那样对providedIn: 'root'
做出反应。 仅当导入服务的模块不是延迟加载时,此选项才会将服务推送到 AppModule(根模块)。
因为定义SomeService
的模块被启动了两次。 (随意将console.log放在这个模块的构造函数中) - 因此服务启动了两次(我自己在我的项目延迟加载平台中遇到了这个问题)。
SomeService
的惰性模块会启动两次? loadChildren
或moduleFactory.create(this.injector)
不保存延迟加载模块的缓存。 他们启动一个模块并将其注入器作为叶子连接到输入注入器。
如果包含SomeService
的模块是从moduleFactory.create
创建的 - 您可以添加一个缓存层以返回缓存的启动延迟加载模块。
例如:
private lazyLoadedModulesCache: Map<Type<any>, NgModuleRef<any>>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.