使用全局注入器的 Angular 7 组件继承 [英] Angular 7 Component Inheritance using a global injector

查看:22
本文介绍了使用全局注入器的 Angular 7 组件继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用 MSDN 博客文章 以简化扩展组件,而无需在 super() 调用中提供所有依赖项.然而,这在 Angular 7 和 Typescript 3 中已经停止工作.

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();
  }
}

然而,从控制台来看,顺序是相反的——首先调用 BaseComponent 的构造函数,然后 boostrapModule() 的承诺被解析.

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

我不确定现在在 Angular 7 中引导​​的行为是否有所不同,正如控制台日志所暗示的那样.使用 Typescript 2 在 Angular 6 中使用的解决方案非常相同,但在版本 7 中它已停止工作.这是基于 MSDN 文章的损坏应用程序的堆栈闪电战:https://stackblitz.com/edit/component-inheritance-angular-7

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

所以根本问题是——如何保证AppInjector.setInjector()发生在AppInjector.getInjector()之前?

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

推荐答案

我已经在 AppModule 中设置了注入器服务,这意味着我将注入 Injector 并将其设置在 AppModule 的构造器中并将注入器服务存储在全局对象中

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);
  }
}

演示

这篇关于使用全局注入器的 Angular 7 组件继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆