Angular 2: How to call a function after get a response from subscribe http.post
Update your get_categories()
method to return the total (wrapped in an observable):
// Note that .subscribe() is gone and I've added a return.get_categories(number) { return this.http.post( url, body, {headers: headers, withCredentials:true}) .map(response => response.json());}
In search_categories()
, you can subscribe the observable returned by get_categories()
(or you could keep transforming it by chaining more RxJS operators):
// send_categories() is now called after get_categories().search_categories() { this.get_categories(1) // The .subscribe() method accepts 3 callbacks .subscribe( // The 1st callback handles the data emitted by the observable. // In your case, it's the JSON data extracted from the response. // That's where you'll find your total property. (jsonData) => { this.send_categories(jsonData.total); }, // The 2nd callback handles errors. (err) => console.error(err), // The 3rd callback handles the "complete" event. () => console.log("observable complete") );}
Note that you only subscribe ONCE, at the end.
Like I said in the comments, the .subscribe()
method of any observable accepts 3 callbacks like this:
obs.subscribe( nextCallback, errorCallback, completeCallback);
They must be passed in this order. You don't have to pass all three. Many times only the nextCallback
is implemented:
obs.subscribe(nextCallback);
You can add a callback function to your list of get_category(...) parameters.
Ex:
get_categories(number, callback){ this.http.post( url, body, {headers: headers, withCredentials:true}) .subscribe( response => { this.total = response.json(); callback(); }, error => { } ); }
And then you can just call get_category(...) like this:
this.get_category(1, name_of_function);
You can code as a lambda expression as the third parameter(on complete) to the subscribe method. Here I re-set the departmentModel variable to the default values.
saveData(data:DepartmentModel){ return this.ds.sendDepartmentOnSubmit(data). subscribe(response=>this.status=response, ()=>{}, ()=>this.departmentModel={DepartmentId:0});}