I am trying to work out a way monitor the result of a HttpClient.Post
observable
from 2 locations without posting data to my server twice.
I've created an example here: https://stackblitz.com/edit/angular-aau9mg
At the moment I have a app.service
which gets data from the server and then on return of the data, sets a value:
public getDump():Observable<any> {
var observable = this.http.get("https://angular-http-guide.firebaseio.com/courses.json");
observable.subscribe(
data => this.someValue = 99,
error => console.log(error)
);
return observable;
}
Then, in the app.component
I want to disable the post button ( dumpInProgress
) and then on retrieving data, set dump
.
getDump(){
this.appService.getDump().subscribe(
(data) => this.dump = data,
() => { },
() => this.dumpInProgress = false
);
}
So this currently works completely as expected and achieves the desired results. The issue I am having that is if you check the network logs when you click the get dump button, you will see that the request is made twice! This is because:
An HttpClient method does not begin its HTTP request until you call subscribe() on the observable returned by that method. This is true for all HttpClient methods. Source
So is it possible to achieve this result without making a second get request?
I think all you need is map
function :
public getDump():Observable<any> {
return this.http.get("https://angular-http-guide.firebaseio.com/courses.json").map(
data => { this.someValue = 99; return data; },
error => console.log(error)
);
}
The reason behind 2 request are ,
this.appService.getDump().subscribe(...) observable.subscribe(...)
This 2 lines of code , you are making 2 calls by subscribing it twice .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.