As a student working on developing a simple WebApp and Server, I have encountered some issues with Http.post and Http.get methods using Observables.
My main challenge is related to posting a boolean value to the server when a button is pressed. While the post process itself works fine, I noticed that every time I press the button, another subscription is added to the observable. I faced a similar issue with my http.get method but managed to resolve it using the following code snippet:
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 located 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())
}
Although not conventional, this approach has helped me manage the subscriptions. On the other hand, my http.post operation is as follows:
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 have tried going through various tutorials on Observables, but I could not find a way to post data to the server without subscribing to the Observable. Any guidance or assistance would be greatly appreciated!
Thank you for your help!