Rak*_*esh 18 typescript angular angular-di
我正在尝试使用APP_INITIALIZER从配置文件加载数据.我收到以下错误:
"Unhandled Promise rejection:this.appInits [i]不是函数; Zone :; Task:Promise.then; Value: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();
}
Run Code Online (Sandbox Code Playgroud)
对我做错的任何帮助?
编辑:
Adam的解决方案修复了原始错误.但现在我看到一个新错误:
TypeError:无法设置undefined的属性'urlList'
据我所知,没有创建ApiConfig的实例.但是我在Angular中加载配置文件时看到的所有示例给出了相同的示例.我想知道如何强制创建ApiConfig类.我怎么能把它变成单身?以下是ApiConfig的用法.
export BaseService {
constructor (private config:ApiConfig){}
public GetUrl (key: string) {
return config.urlList[key];
}
}
Run Code Online (Sandbox Code Playgroud)
答: 看起来在上面的代码中创建promise的方式存在问题.我修改了我的loadconfig()方法,如链接中所示:https://gist.github.com/fernandohu/122e88c3bcd210bbe41c608c36306db9 这解决了我的问题.
Ada*_*dam 44
我认为这是因为您需要在export函数语句中返回该函数:
export function apiConfigProvider(config: ApiConfig) {
return () => config.loadConfig();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7380 次 |
| 最近记录: |