Angular 7 Component Inheritance using a global injector

淺唱寂寞╮ 提交于 2019-11-30 17:55:19

问题


I've been using the approach described in an MSDN blog post to simplify extending components without needing to provide all the dependencies in the super() call. However this has stopped working in Angular 7 with Typescript 3.

So what's happening is that after bootstrapping, I'm trying to store the injector in a service and afterwards I try to retrieve it.

platformBrowserDynamic().bootstrapModule(AppModule).then(ref => {
  // Store module's injector in the AppInjector class
  console.log('Expected #1: storing app injector');
  AppInjector.setInjector(ref.injector);
})

and then in the base component I fetch the stored injector

export class BaseComponent {
  constructor() {
    console.log('Expected #2: retrieving stored injector');
    const injector = AppInjector.getInjector();
  }
}

However looking at the console, the order is reversed – first the BaseComponent's constructor is called whichafter the promise of boostrapModule() is resolved.

I'm not sure if bootstrapping is behaving differently now in Angular 7, as the console logs hint. The very same solution used to work in Angular 6 with Typescript 2, but with version 7 it has stopped working. Here's a stackblitz of the broken app based on the MSDN article: https://stackblitz.com/edit/component-inheritance-angular-7

So the fundamental question is – how to guarantee that AppInjector.setInjector() happens before AppInjector.getInjector()?


回答1:


I have set the injector service in AppModule and that mean I will inject Injector and set it in the constractor of AppModule and store the injector service in global object

export class AppModule { 
  constructor(injector:Injector){
  // Store module's injector in the AppInjector class
  console.log('Expected #1: storing app injector');
  AppInjector.setInjector(injector);
  }
}

demo



来源:https://stackoverflow.com/questions/53185211/angular-7-component-inheritance-using-a-global-injector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!