I'm trying to wrap the http service in angular 2 using this code:
@Injectable()
export class HttpSuperService {
private baseUrl: string;
constructor(private http: Http) {
}
get(url: string): Observable<string> {
return (
this.baseUrl ?
Observable.of(this.baseUrl) :
this.http.get('/config/').map((res: Response) => res)
)
.flatMap((res: any) => {
this.baseUrl = res._body;
return this.http.get(this.baseUrl + url)
.map((res2: Response) => res2.json());
});
}
}
What I'm trying to do is making the first request to get the baseUrl for the application (the API is on another URL) but only making that request once (the first time).
it works on the first request but the second request (IE when another component is using the same service) is not working since there is something wrong with the "Observable.of". I get that i need to use Response in some way instead of the string....That lead me to start thinking about this approach. Is there a better way to do this?
This solution works but feels a little to verbose since I plan to add other methods (POST, PUT) to this service as well:
@Injectable()
export class HttpSuperService {
private baseUrl: string;
constructor(private http: Http) {
}
get(url: string): Observable<string> {
if (this.baseUrl) {
return this.http.get(this.baseUrl + url).map((res2: Response) => res2.json());
}
return this.http.get('/config/').map((res: Response) => res)
.flatMap((res: any) => {
this.baseUrl = res._body;
return this.http.get(this.baseUrl + url).map((res2: Response) => res2.json());
});
}
}