Angular:如何正确实现APP_INITIALIZER

前端之家收集整理的这篇文章主要介绍了Angular:如何正确实现APP_INITIALIZER前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个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();
}

猜你在找的Angularjs相关文章