Мне нужно вызвать метод после получения данных из http post запроса
сервис: request.service.TS
get_categories(number){
this.http.post( url, body, {headers: headers, withCredentials:true})
.subscribe(
response => {
this.total = response.json();
}, error => {
}
);
}
компонент: 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();
}
Работает только если я меняю на:
сервис: 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 => {
}
);
}
Но мне нужно вызвать метод send_catagories()
внутри компонента после вызова this.get_categories(1);
следующим образом
компонент: categories.TS
search_categories() {
this.get_categories(1);
this.send_catagories(response);
}
Что я делаю не так?
Обновите метод get_categories()
, чтобы он возвращал общее количество (обернутое в наблюдаемую величину):
// 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()
вы можете подписаться на наблюдаемую, возвращаемую get_categories()
(или вы можете продолжать преобразовывать ее, цепляя больше операторов 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")
);
}
Обратите внимание, что вы подписываетесь только ОДИН раз, в конце.
Как я уже говорил в комментариях, метод .subscribe()
любой наблюдаемой принимает 3 обратных вызова, как это:
obs.subscribe(
nextCallback,
errorCallback,
completeCallback
);
Они должны быть переданы в этом порядке. Вам не обязательно передавать все три. Во многих случаях реализуется только nextCallback
:
obs.subscribe(nextCallback);
Вы можете добавить функцию обратного вызова к списку параметров get_category(...).
Например:
get_categories(number, callback){
this.http.post( url, body, {headers: headers, withCredentials:true})
.subscribe(
response => {
this.total = response.json();
callback();
}, error => {
}
);
}
А затем вы можете просто вызвать get_category(...) следующим образом:
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();
);
}
тогда
this.get_category(1).subscribe(t=> {
this.callfunc();
});