Reputation: 3548
I created a http client where I ovverride the http post method:
post(url, data):Observable<Response> {
let headers = new Headers();
this.createAuthorizationHeader(headers);
var response = this.http.post("\\services" + url, data, {
headers: headers
});
return this.handleResponse(response);
}
private handleResponse(responseO : Observable<Response>) : Observable<Response> {
responseO.do(response =>
{
if (response.url.includes("LoginPage.html")) {
window.location.replace("../LoginPage.html");
}
});
return responseO;
}
Then In my service I subscribe:
return this.http.post("/dummy", params).subscribe(response => callback(response.json()));
In my httpClient if I return the response instead of handleResponse(response) everything works fine. What I need though is for all my requests to do the check in the responseO.do(..) besides the current behaviour.
I also tried response.share(); and subscribe to this object but that doesn't work either.
Is there a way to achieve what I'm looking for? Thanks.
Upvotes: 0
Views: 1000
Reputation: 4683
If you want to manipulate the observable's stream data, instead of using do
, you should probably use map
. It's the more 'reactive' way of manipulating a stream.
post(url, data):Observable<Response> {
let headers = new Headers();
this.createAuthorizationHeader(headers);
var response = this.http.post("\\services" + url, data, {
headers: headers
});
return response.map(res => handleResponse(res));
}
private handleResponse(responseO : Response) : Response {
if (response.url.includes("LoginPage.html")) {
window.location.replace("../LoginPage.html");
}
return responseO;
}
I'd also like to recommend against using window.location.replace
in an Angular 2 app, since it will force the page to refresh, which means having to restart the application. If you use the Angular router to change the route, you won't have to wait for the app to load when you navigate.
Upvotes: 1
Reputation: 14257
Sure you're not subscribing to the Observable with the do
interceptor.
Return the Observable with the do
interceptor:
post(url, data):Observable<Response> {
let headers = new Headers();
this.createAuthorizationHeader(headers);
var response = this.http.post("\\services" + url, data, {
headers: headers
});
return this.handleResponse(response);
}
private handleResponse(responseO : Observable<Response>) {
return responseO.do(response => {
if (response.url.includes("LoginPage.html")) {
window.location.replace("../LoginPage.html");
}
});
}
Upvotes: 1