Reputation: 206
I have a few problems concerning Http.post and Http.get with Observables. I'm a student and I'm trying to write a simple WebApp and a Server.
I want to post a boolean on my Server if I press a button. The post process does work but everytime I press the button I subscribe another time to the observable. I had the same problem with my http.get method and resolved the problem with this code.
getdata() {
if(this.subscribtion2 === null){
this.isValid = false;
this.subscribtion2 = this.service.get2().subscribe(
daten => {
this.jsonobj = daten;
this.message =
[
this.jsonobj.data.message1,
];
console.log('subscribe')
;
this.myModelneu = this.message[0];
},
err => this.handleError(err),
() => console.log('Simple GET completed')
);
}else
{
this.isValid = true;
console.log('unsubscribe')
this.subscribtion2.unsubscribe();
this.subscribtion2 = null;
}
}
The get2() method is in a different class.
get2() {
return Observable.interval(3000)
.switchMap(() => this.http.get('http://127.0.0.1:3000/daten/2'))
.map(res => res.json())
}
I don't think that is the common way but I can't find another. My http.post look likes this :
post(json: boolean) {
console.log('post executed');
console.log(JSON.stringify(json));
return this.http.post('http://127.0.0.1:3000/login', { json })
.subscribe();
}
I tried to understand the tutorials with Observables but I did not find how to post data on the server without subscribing to the Observable.
Thanks for your help!
Upvotes: 0
Views: 465
Reputation: 14395
The http
calls, specifically get
and post
return an observable that completes with the result, hence you don't need to unsubscribe. On completion the subscription is terminated.
Upvotes: 2