71

I am trying to use APP_INITIALIZER TO load data from config file. I'm getting following error:

"Unhandled Promise rejection: this.appInits[i] is not a function ; Zone: ; Task: Promise.then ; Value: TypeError: this.appInits[i] is not a function"

Code:

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();
}

Any help on what I'm doing wrong?

Edit:

Adam's solution fixed the original error. But now I see a new error:

TypeError: Cannot set property 'urlList' of undefined

As I understand there is no instance of ApiConfig created. But all the examples I see in loading the config file in Angular give same example. I wonder how to force the creation of ApiConfig class. And how I can make it a singleton? Below is the usage of ApiConfig.

export BaseService { 
constructor (private config:ApiConfig){} 

public GetUrl (key: string) { 
   return config.urlList[key]; 
} 

}

Answer: It looks like there is an issue with the way promise is created in above code. I modified my loadconfig() method as given in the link: https://gist.github.com/fernandohu/122e88c3bcd210bbe41c608c36306db9 this resolved my problem.

Rakesh
  • 803
  • 1
  • 6
  • 11

1 Answers1

117

I think this is because you need to return the function in your export function statement:

export function apiConfigProvider(config: ApiConfig) {
   return () => config.loadConfig();
}
Adam
  • 2,446
  • 1
  • 13
  • 16
  • Thanks for your suggestion. It fixed my original error. However now I get another error. It says "TypeError: Cannot set property 'urlList' of undefined". As I understand there is no instance of ApiConfig created. But all the examples I see in loading the config file in Angular give same example. I wonder how to force the creation of ApiConfig class. And how I can make it a singleton. I'm adding ApiConfig to Providers list in AppModule. – Rakesh Sep 06 '17 at 13:49
  • 2
    @Rakesh if this answer solved your problem, mark it as accepted then ask another question. You shouldn't ask multiple questions in 1 question. https://meta.stackexchange.com/questions/156900/whats-the-policy-on-follow-up-questions – eko Sep 07 '17 at 06:32
  • 4
    This blog post has a full APP_INITIALIZER example: https://www.intertech.com/Blog/angular-4-tutorial-run-code-during-app-initialization/ – codeape Jan 17 '18 at 09:15