【问题标题】:Angular Mobile depending ServiceAngular 移动依赖服务
【发布时间】:2020-10-15 22:56:59
【问题描述】:

我想问是否可以在构造函数中加载“动态”参数? 例如,我的 app.module 中有一个模块,我通过环境变量加载。

@NgModule({
  imports: [
    environment.mobile ? MobileModule : []
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}

在这个 MobileModule 中有一个服务,我用于登录和其他东西。 问题是我不想只在移动设备中的 Web 环境中使用这些服务。我在 Mobile 中重用 Web Components,所以我在这些组件中使用 MobileService。 如果我使用 Web 环境启动我的项目,我会收到一个错误,原因是 No Provider for MobileService 因为我在构造函数中加载它。

  constructor(
    router: Router,
    public mobileService: MobileService,
  ) {}

有没有办法在构造函数中动态加载服务?

真的很愚蠢的问题...我想创建一个移动组件和一个 Web 组件,但仅针对这些服务,可能只调用一次,我认为这有点过头了。

如果最好检查一下然后做这些事情

if (this.mobileService) {....}

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    对于可选依赖项,您需要使用@Optional() 注释构造函数参数。

    例如:

    constructor(router: Router, @Optional() public mobileService: MobileService) {
      if (this.mobileService) {....}
    }
    

    您可以在official documentation阅读更多内容。

    【讨论】:

      猜你喜欢
      • 2019-03-04
      • 2018-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-17
      • 1970-01-01
      • 1970-01-01
      • 2020-08-25
      相关资源
      最近更新 更多