I'm working in angular 4 and I have an appConfigService that provides the url of the api application from an settings.json file, something like:
private appConfig: AppConfig;
constructor(private http: Http) {
this.loadConfig().subscribe(e => this.appConfig = e);
}
public loadConfig(): Observable<AppConfig> {
return this.http
.get("appsettings.json")
.map(this.mapAppConfig)
.catch(this.handleError);
}
then i use that url for all my following requests.
it work fine for requests sent after the url has been returned, however I am having issues with the requests sent when the page loads (and the url has not been retrieved yet).
I am aware I can use the flatmap function in the services that load at the startup but i find myself creating basically two implementations of the same function:
private getBasicRequest(offset: number = 0, limit:number = 0 ): Observable<Response>{
if (!this.appConfigService.isAppConfigValid()) {
var urlObserver = this.appConfigService.loadConfig();
var request = urlObserver
.flatMap(responseFromConfigService =>
this.http.get(responseFromConfigService.apiBaseAddress + "/entries/" + this.searchTerm + "?offset=" + offset + "&limit=" + limit));
return request;
} else {
var url = this.appConfigService.getApiLink("entries/" + this.searchTerm + "?offset=" + offset + "&limit=" + limit);
return this.http.get(url);
}
}
What would be a better way to deal with this scenario? I tried to get the appConfigService service to start at 'startup' that would fix my issue but it didn't work.