Preciso de chamar um método depois de obter os dados do pedido do posto http
**serviço: request.service.TS***
get_categories(number){
this.http.post( url, body, {headers: headers, withCredentials:true})
.subscribe(
response => {
this.total = response.json();
}, error => {
}
);
}
**componente: categorias.TS***
search_categories() {
this.get_categories(1);
//I need to call a Method here after get the data from response.json() !! e.g.: send_catagories();
}
Só funciona se eu mudar para:
**serviço: request.service.TS***
get_categories(number){
this.http.post( url, body, {headers: headers, withCredentials:true})
.subscribe(
response => {
this.total = response.json();
this.send_catagories(); //here works fine
}, error => {
}
);
}
Mas preciso de chamar o método send_catagories()
dentro do componente após a chamada this.get_categories(1);
assim
componente: categorias.TS
search_categories() {
this.get_categories(1);
this.send_catagories(response);
}
O que estou a fazer mal?
Actualize o seu get_categories()
método para retornar o total (embrulhado num observável):
// 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());
}
Em search_categories()
, pode subscrever o observável devolvido por get_categories()
(ou pode continuar a transformá-lo encadeando mais operadores RxJS):
// 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-se que somente subscreve ONCE, no final.
Como disse nos comentários, o método .subscribe()
de qualquer observável aceita 3 callbacks como este:
obs.subscribe(
nextCallback,
errorCallback,
completeCallback
);
Devem ser aprovados por esta ordem. Não'não têm de passar os três. Muitas vezes, apenas o nextCallback
é implementado:
obs.subscribe(nextCallback);
Pode adicionar uma função de revogação à sua lista de parâmetros get_category(...).
Ex:
get_categories(number, callback){
this.http.post( url, body, {headers: headers, withCredentials:true})
.subscribe(
response => {
this.total = response.json();
callback();
}, error => {
}
);
}
E depois pode simplesmente chamar get_category(...) desta forma:
this.get_category(1, name_of_function);