Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2:How to detect the completion of HTTP request?

I have 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 a get service for same model:

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

Problem: I have set up my component in such a manner that first put request occurs-which changes my table in Db. Immediately after that, get request occurs which gets the table entries. But, before the Put request completes, get completes its execution.

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

How to detect whether my http request is completed in Angular 2?

Edit: From the answer of @Gunter, I provided three call backs to my subscribe method of put:

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 completed method is:

 completed(){
alert("Request completed");
}
like image 857
Karan Desai Avatar asked Aug 24 '16 10:08

Karan Desai


1 Answers

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 last one is called when the observable is closed. Because http.xxx() always emits only one value and then closes the observable, the first and the last are pretty much the same.

There is also the finally() operator that is called in any case (success and error).

like image 194
Günter Zöchbauer Avatar answered Oct 26 '22 05:10

Günter Zöchbauer