加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular:如何正确实现APP_INITIALIZER

发布时间:2020-12-17 17:24:05 所属栏目:安全 来源:网络整理
导读:我有一个Angular 5.2.0应用程序. 我查找了如何在应用程序启动之前实现APP_INITIALIZER来加载配置信息. 这是app.module的摘录: providers: [ ConfigurationService,{ provide: APP_INITIALIZER,useFactory: (configService: ConfigurationService) = () = co
我有一个Angular 5.2.0应用程序.
我查找了如何在应用程序启动之前实现APP_INITIALIZER来加载配置信息.
这是app.module的摘录:

providers: [
    ConfigurationService,{
        provide: APP_INITIALIZER,useFactory: (configService: ConfigurationService) =>
            () => configService.loadConfigurationData(),deps: [ConfigurationService],multi: true
    }
],

这里是configuration.service:

import { Injectable,Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { Configuration } from './configuration';

@Injectable()
export class ConfigurationService {
    private readonly configUrlPath: string = 'Home/Configuration';
    private configData: Configuration;

    constructor(
        private http: HttpClient,@Inject('BASE_URL') private originUrl: string) { }

    loadConfigurationData() {
        this.http
            .get<Configuration>(`${this.originUrl}${this.configUrlPath}`)
            .subscribe(result => {
                this.configData = {
                    test1ServiceUrl: result["test1ServiceUrl"],test2ServiceUrl: result["test2ServiceUrl"]        
                }
            });
    }

    get config(): Configuration {
        return this.configData;
    }
}

以下是使用configData的组件构造函数的示例:

export class TestComponent {
    public test1ServiceUrl: string;

    constructor(public configService: ConfigurationService) {
        this.test1ServiceUrl = this.configService.config.test1ServiceUrl;
    }
}

它适用于< router-outlet>< / router-outlet>中定义的所有组件.但是< router-outlet>< / router-outlet>之外的组件中的相同实现方式不起作用.
当我调试它不起作用的组件的相应构造函数时,它说configService为null.
为什么APP_INITIALIZER在< router-outlet>< / router-outlet>内的组件的构造函数之前执行?被调用但不在< router-outlet>< / router-outlet>?之外的组件的构造函数之前

解决方法

由于APP_INTIALIZER works如何,预计异步初始化器会返回promise,但是您的APP_INTIALIZER多提供程序的实现不会因为loadConfigurationData函数没有返回任何内容.

它应该是这样的:

loadConfigurationData(): Promise<Configuration> {
  return this.http.get<Configuration>(`${this.originUrl}${this.configUrlPath}`)
  .do(result => {
    this.configData = result;
  })
  .toPromise();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读