Angular 2: How to determine the end of an HTTP request?

I have the following Http put request in Angular 2:

... ... private Url='api/demo/' UpdatState(obj: Model) { let headers = new Headers({ 'Content-Type': 'application/json', }); return this.http.put(this.Url + obj.Id, JSON.stringify(obj), { headers: headers }).map(res => res.json().data).subscribe(..); } 

and get a service for the same model:

  getState(){ return this.http.get(this.Url) .map(response => response.json()); } 

Problem: I configured my component so that the first query is executed, which changes my table in Db. Immediately after that, it receives a query that receives records in a table. But before the Put request completes, complete it.

 ... ... onSomeEvent(){ this.updatestate(obj); this.getState(); } ... ... 

How to determine if my HTTP request has completed in Angular 2?

Edit : From @Gunter answer, I provided three calls for my subscription method:

 UpdatState(obj: Model) { let headers = new Headers({ Content-Type': 'application/json', }); return this.http.put(this.Url + obj.Id, JSON.stringify(obj), { headers: headers }) .map(res => res.json().data) .subscribe( (a) => { this.b = a }, //b is my local array err => { this.error = err; }, //error is my local string variable () => { this.completed(); } ); } 

And my finished method:

  completed(){ alert("Request completed"); } 
+6
source share
1 answer

You can pass three callbacks to subscribe(...)

 this.http.put(...).subscribe( value => this.doSomething(value), // called for each value error => this.handleError(err), () => this.completed() }) 

The latter is called when the observable is closed. Since http.xxx() always emits only one value and then closes the observable, the first and last are approximately the same.

There is also a finally() statement that is called anyway (success and error).

+5
source

All Articles