Http post isteğinden veri aldıktan sonra bir yöntem çağırmam gerekiyor
hizmet: request.service.TS
get_categories(number){
this.http.post( url, body, {headers: headers, withCredentials:true})
.subscribe(
response => {
this.total = response.json();
}, error => {
}
);
}
bileşen: categories.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();
}
Sadece değiştirirsem çalışır:
hizmet: 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 => {
}
);
}
Ancak this.get_categories(1);
çağrısından sonra bileşenin içindeki send_catagories()
yöntemini şu şekilde çağırmam gerekiyor
bileşen: categories.TS
search_categories() {
this.get_categories(1);
this.send_catagories(response);
}
Neyi yanlış yapıyorum?
get_categories()` yönteminizi toplamı geri döndürmek için güncelleyin (bir gözlemlenebilire sarılmış olarak):
// 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());
}
search_categories()de,
get_categories()` tarafından döndürülen gözlemlenebilire abone olabilirsiniz (veya daha fazla RxJS operatörünü zincirleyerek dönüştürmeye devam edebilirsiniz):
// 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")
);
}
Sonunda sadece BİR KEZ abone olacağınızı unutmayın.
Yorumlarda söylediğim gibi, herhangi bir gözlemlenebilirin .subscribe()
yöntemi bunun gibi 3 geri çağırma kabul eder:
obs.subscribe(
nextCallback,
errorCallback,
completeCallback
);
Bu sırayla geçilmelidirler. Üçünü de geçmek zorunda değilsiniz. Çoğu zaman sadece nextCallback
uygulanmaktadır:
obs.subscribe(nextCallback);
get_category(...) parametreleri listenize bir geri arama işlevi ekleyebilirsiniz.
Ex:
get_categories(number, callback){
this.http.post( url, body, {headers: headers, withCredentials:true})
.subscribe(
response => {
this.total = response.json();
callback();
}, error => {
}
);
}
Ve sonra get_category(...) işlevini şu şekilde çağırabilirsiniz:
this.get_category(1, name_of_function);
get_categories(number){
return this.http.post( url, body, {headers: headers, withCredentials:true})
.map(t=> {
this.total = t.json();
return total;
}).share();
);
}
sonra
this.get_category(1).subscribe(t=> {
this.callfunc();
});