【问题标题】:How to pass injection token to nested service using SCAM approach (Single Component Angular Module)?如何使用 SCAM 方法(单组件 Angular 模块)将注入令牌传递给嵌套服务?
【发布时间】:2021-08-30 08:17:49
【问题描述】:

我一直在使用 SCAM(单组件 Angular 模块)方法,但在将 injection token 从父模块传递到子模块时遇到了问题。

我有一个 ScamService,其中注入了 httpClientbaseUrl

import { HttpClient, HttpClientModule } from '@angular/common/http';
import { Injectable, Inject, NgModule, ModuleWithProviders } from '@angular/core';
import { BASE_URL } from './injection.tokens';

@Injectable()
export class ScamService {
  constructor( @Inject(BASE_URL) private baseUrl, private httpClient: HttpClient ) {}

  public getData() {
    return this.httpClient.get(`${this.baseUrl}/rest-of-endpoint`);
  }
}

@NgModule({
  imports: [HttpClientModule]
})
export class ScamServiceModule {
  public static forRoot(baseUrl): ModuleWithProviders<ScamServiceModule> {
    return {
      ngModule: ScamServiceModule,
      providers: [{
          provide: BASE_URL,
          useValue: baseUrl
      }]
    };
  }
}

要向模块提供 BASE_URL 令牌,我需要创建返回 ModuleWithProviders 的静态方法。在那里我可以为令牌分配一个值。没关系。

接下来,我想在一个组件中使用该服务,所以我将 ScamServiceModule 导入到 ScamComponentModule 中:

import { Component, ModuleWithProviders, NgModule } from '@angular/core';
import { ScamService, ScamServiceModule } from './scam.service';

@Component({//...})
export class ScamComponent {
  constructor(private scamService: ScamService) {}
}

@NgModule({
  imports: [
    ScamServiceModule.forRoot(
      `The url I would like to pass is not in the environments, 
       I need to take it from forRoot of ScamComponentModule`
    )
  ]
})
export class ScamComponentModule {
  public static forRoot(baseUrl): ModuleWithProviders<ScamComponentModule> {
    // how to tell ScamServiceModule what the value of baseUrl is?
  }
}

现在我需要为其提供基本网址。所以我应该调用 ScamServiceModule.forRoot('some-url')。如果我知道组件级别的 url,那就太好了。

但是url需要通过ScamComponentModuleforRoot方法传递。

你对如何传递baseUrl有什么建议吗?

提前谢谢你!

【问题讨论】:

    标签: angular dependency-injection angular-module injection-tokens


    【解决方案1】:

    该问题与 SCAM 方法无关。

    这只是提供依赖关系。该问题的解决方案是在 Angular Providers 数组中使用“deps”属性以及“provide”和“useValue”。

    【讨论】:

      猜你喜欢
      • 2020-11-14
      • 1970-01-01
      • 2021-11-13
      • 2020-11-21
      • 2016-11-02
      • 1970-01-01
      • 1970-01-01
      • 2016-03-25
      • 1970-01-01
      相关资源
      最近更新 更多