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

时间:2017-02-15 00:38:30

标签: javascript angular typescript promise subscribe

我需要在从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);
}

我做错了什么?

5 个答案:

答案 0 :(得分:34)

将您的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()返回的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);

答案 1 :(得分:7)

您可以在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);

答案 2 :(得分:3)

您可以将lambda表达式编码为subscribe方法的第三个参数(完成后)。在这里,我将departmentModel变量重新设置为默认值。

saveData(data:DepartmentModel){
  return this.ds.sendDepartmentOnSubmit(data).
  subscribe(response=>this.status=response,
   ()=>{},
   ()=>this.departmentModel={DepartmentId:0});
}

答案 3 :(得分:2)

您也可以使用新的Subject来做到这一点:

打字稿:

let subject = new Subject();

get_categories(...) {
   this.http.post(...).subscribe( 
      (response) => {
         this.total = response.json();
         subject.next();
      }
   ); 

   return subject; // can be subscribed as well 
}

get_categories(...).subscribe(
   (response) => {
     // ...
   }
);

答案 4 :(得分:1)

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