"this.appInits [i]"不是一个函数

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)

  • 这篇博文有一个完整的 APP_INITIALIZER 示例:https://www.intertech.com/Blog/angular-4-tutorial-run-code-during-app-initialization/ (3认同)
  • @Rakesh如果这个答案解决了你的问题,请将其标记为已接受,然后再提出另一个问题.你不应该在一个问题中提出多个问题.https://meta.stackexchange.com/questions/156900/whats-the-policy-on-follow-up-questions (2认同)