【问题标题】:Get value for provider from service从服务中为提供商获取价值
【发布时间】:2019-06-21 12:55:33
【问题描述】:

我正在尝试将一些值(我从 http 请求中获得)从另一个服务分配给 app.module.ts 中的提供者令牌。

我的服务如下所示:

@Injectable()
export class AppConfigService {
      private appConfig: AppConfig;

      constructor(private http: HttpClient) {}

      loadConfigurationData = () => {
        this.http.get('assets/config/config.json').subscribe(
          (response: AppConfig) => {
            this.appConfig = response;
          },
          error => {
            this.appConfig = {
              baseHref: '/'
            };
          }
        );
};

      getBaseHref(): string {
        return this.appConfig.baseHref;
      }
}

在我的app.module.ts 中,我试图像这样获得这个值`baseHref`:

@NgModule({  
providers: [
        ...
        AppConfigService,
        {
          provide: APP_INITIALIZER,
          useFactory: (appConfigService: AppConfigService) => () => {
            appConfigService.loadConfigurationData();
          },
          deps: [AppConfigService],
          multi: true
        },
        {
          provide: APP_BASE_HREF,
          useFactory: getBaseHref,
          deps: [AppConfigService],
          multi: true
        },
        ...
      ],
})

export function getBaseHref(appConfigService: AppConfigService): string {
      return appConfigService.getBaseHref();
}

但我收到一个错误:`Cannot read property 'baseHref' of undefined`。

看起来服务没有初始化,但为什么?将此变量从服务传递给提供者的最佳方式是什么?

【问题讨论】:

  • 你应该将请求返回的observable返回给调用组件,你可以手动订阅或者通过安全导航操作符直接在模板中使用observable。

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


【解决方案1】:

由于您依赖异步数据来更新您的 appconfig 变量,因此最初它是未定义的

Appconfig 必须初始化:

 private appConfig: AppConfig = {baseref: null} // or default

【讨论】:

  • 从服务中的 http 请求更新后,如何将此值分配给提供者?
猜你喜欢
  • 2020-09-21
  • 1970-01-01
  • 2012-10-27
  • 2021-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-23
相关资源
最近更新 更多