我需要在从http post请求中获得数据后调用一个方法
服务:request.service.TS
get_categories(number){
this.http.post( url, body, {headers: headers, withCredentials:true})
.subscribe(
response => {
this.total = response.json();
}, error => {
}
);
}
构件:category.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 => {
}
);
}
但我需要在调用this.get_categories(1);
之后,在组件内部调用send_catagories()
方法,就像这样
组件:category.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);