【问题标题】:Should there be code in the constructor of an @NgModule and if so what are some reasons for it?@NgModule 的构造函数中是否应该有代码,如果有,有什么原因?
【发布时间】:2019-08-08 19:55:04
【问题描述】:

可以这样做,并且代码在模块加载时运行:

import { NgModule } from '@angular /core';

@NgModule({...})
export class SomeNgModule {
  constructor(providedService: ProvidedService) {
        providerService.iCanDoThis('?');
  }
}

但是如果我想初始化代码,我不应该使用APP_INITIALIZER 或其他一些钩子吗?

我找不到一个很好的理由说明什么时候这是一个很好的用途以及它会有什么帮助。

另一个很好的问题可能是:这段代码何时会在 Angular 的应用程序生命周期中执行

【问题讨论】:

标签: angular design-patterns ng-modules


【解决方案1】:

我在这种情况下使用这种注入方式,我想在我的自定义类中使用 Angular 服务,但我不能直接在构造函数中注入它。因此我需要一个Injector 的实例。

import {Injector, NgModule} from '@angular/core';

export let InjectorInstance: Injector;


@NgModule({
  /* *** */
})
export class FeatureModule {
  constructor(private injector: Injector) {
    InjectorInstance = this.injector;
  }
}

然后在我的自定义类中使用它来注入这样的 Angular 服务:

import {InjectorInstance} from 'pat-to-feature-module';


export class MyCustomClass{

  getHttpService = () => {
    return InjectorInstance.get<HttpClient>(HttpClient);
  };
}

这样,我确保我使用(注入)由 Angular 创建的服务。也许还有其他方法可以使用此功能。

【讨论】:

  • 为什么不把 MyCustomClass 做成 Angular 服务,让 DI 处理 HttpClient?嗯,也许我从来没有遇到过实例化类需要它的情况。
  • 假设我有 30 多个作为实体的自定义类。 (用户、令牌、产品、客户等)。然后我需要能够将 API 响应映射到这些类。所以我不希望它们成为服务(可注入),因为我不注入它们。正如我所说,我不确定这是否是最正确的方法,但它确实满足我在这种情况下的需求。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-20
  • 2021-05-21
  • 2019-10-16
相关资源
最近更新 更多