0

I'm new to rxjs. what is the problem with this code that subscribe method not work correctly.

this.http.postReq(this.api, data)
.subscribe((value) => {
  this.toastr.success(value, "Successfull");
  this.isLoading = false;
}, (err) => {
  this.toastr.error(err.error, "Error")
  this.isLoading = false;
}).unsubscribe();

}

but when remove ".unsubscribe()" its work correctly.

an example that work correctly in this manner.

ihsan
  • 59
  • 9
  • the call is asynchronous so , your request is unsubscribed even before getting the response. – CruelEngine Feb 19 '18 at 08:26
  • how can i unsubscribe async request – ihsan Feb 19 '18 at 08:27
  • 3
    You don't need to unsubscribe here. Angular's HttpClient, which I assume you are using, completes the observable when the response is sent. A completed observable cleans up after itself automatically. – Ingo Bürk Feb 19 '18 at 08:35

1 Answers1

1

To do this :

let someSubscription = this.http.postReq(this.api, data)
.subscribe((value) => {
  this.toastr.success(value, "Successfull");
  this.isLoading = false;
someSubscription.unsubscribe();
}, (err) => {
  this.toastr.error(err.error, "Error")
  this.isLoading = false;
});

So now , your request is unsubscribed after getting the response (which you want) .

CruelEngine
  • 2,701
  • 4
  • 23
  • 44