我正在尝试使用APP_INITIALIZER从配置文件加载数据。我收到了以下错误:
"未处理的承诺拒绝:this.appInits [i]不是函数; 区域:;任务:Promise.then;值:TypeError:this.appInits [i] 不是一个功能"
代码:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Rx';
@Injectable()
export class ApiConfig {
private urlList: any = null;
constructor(private http: Http) {
}
public getUrl(key: any) {
return this.urlList[key];
}
public loadConfig(){
let retPromise: Promise<any> = this.http.get('./assets/config/api-config.json')
.map(res => res.json()).toPromise();
retPromise.then(resp => this.urlList=resp.urlList);
//this.urlList = retPromise.urlList;
return retPromise;
}
}
export function apiConfigProvider(config: ApiConfig) {
config.loadConfig();
}
对我做错的任何帮助?
修改
亚当的解决方案修复了原始错误。但现在我看到了一个新错误:
TypeError:无法设置属性&#39; urlList&#39;未定义的
据我所知,没有创建ApiConfig的实例。但是我在Angular中加载配置文件时看到的所有示例给出了相同的示例。我想知道如何强制创建ApiConfig类。我怎么能把它变成单身? 以下是ApiConfig的用法。
export BaseService {
constructor (private config:ApiConfig){}
public GetUrl (key: string) {
return config.urlList[key];
}
}
答案: 看起来在上面的代码中创建promise的方式存在问题。我修改了链接中给出的loadconfig()方法:https://gist.github.com/fernandohu/122e88c3bcd210bbe41c608c36306db9这解决了我的问题。
答案 0 :(得分:36)
我认为这是因为您需要在导出函数语句中返回该函数:
export function apiConfigProvider(config: ApiConfig) {
return () => config.loadConfig();
}