Angular 2:从订阅 http.post 获得响应后如何调用函数

新手上路,请多包涵

从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);
}

我做错了什么?

原文由 Louise 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 974
2 个回答

更新您的 get_categories() 方法以 返回 总数(包装在 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());
}

search_categories() 中,您可以订阅 get_categories() 返回的 observable(或者您可以通过链接更多 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")
    );
}

请注意,您最后 只订阅 ONCE

就像我在评论中所说的那样,任何 observable 的 .subscribe() 方法都接受 3 个这样的回调:

 obs.subscribe(
  nextCallback,
  errorCallback,
  completeCallback
);

它们必须按此顺序通过。您不必通过所有三个。很多时候只实现了 nextCallback

 obs.subscribe(nextCallback);

原文由 AngularChef 发布,翻译遵循 CC BY-SA 3.0 许可协议

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();
});

原文由 pixelbits 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏