Angular 2 - Services consuming others services before call a method

后端 未结 1 1192
执念已碎
执念已碎 2020-11-30 14:25

I\'ve this scenario.

backend.json

{
\"devServer\": \"http://server1/\'\",
\"proServer\" : \"http://server2/\'\",
\"use\" :  \"devServer\"
}


        
相关标签:
1条回答
  • 2020-11-30 15:06

    I think that you could preload such hints at the application startup. For this, you could leverage the APP_INITIALIZER service. The application will wait for the returned promise to be resolved before actually starting.

    Here is a sample:

    provide(APP_INITIALIZER, {
      useFactory: (service:GlobalService) => () => service.load(),
      deps:[GlobalService, HTTP_PROVIDERS], multi: true
    })
    

    The load method would like something like that:

    load():Promise<Site> {
      var promise = this.http.get('config.json').map(res => res.json()).toPromise();
      promise.then(config => this.devServer = config.devServer);
      return promise;
    }
    

    Then you can directly use the devServer (synchronously)...

    See this issue on github for more details:

    • https://github.com/angular/angular/issues/9047
    0 讨论(0)
提交回复
热议问题