简体   繁体   English

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

[英]Angular 2: How to call a function after get a response from subscribe http.post

I need to call a method after get the data from the http post request 我需要在从http post请求中获取数据后调用方法

service: request.service.TS service:request.service.TS

get_categories(number){
 this.http.post( url, body, {headers: headers, withCredentials:true})
    .subscribe( 
      response => {
        this.total = response.json();

      }, error => {
    }
  ); 

}

component: categories.TS 组件: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();
}

Only works if I change to: 只有在我改为:

service: request.service.TS service: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 => {
    }
  ); 

}

But I need to call the method send_catagories() inside of component after call this.get_categories(1); 但是我需要在调用send_catagories() this.get_categories(1);之后调用组件内部的方法send_catagories() this.get_categories(1); like this 像这样

component: categories.TS 组件:categories.TS

search_categories() {

this.get_categories(1);
this.send_catagories(response);
}

What I doing wrong? 我做错了什么?

Update your get_categories() method to return the total (wrapped in an observable): 更新你的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());
}

In search_categories() , you can subscribe the observable returned by get_categories() (or you could keep transforming it by chaining more RxJS operators): search_categories() ,您可以订阅get_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")
    );
}

Note that you only subscribe ONCE , at the end. 请注意,您最后只订阅了ONCE

Like I said in the comments, the .subscribe() method of any observable accepts 3 callbacks like this: 就像我在评论中所说的.subscribe() ,任何observable的.subscribe()方法接受3个这样的回调:

obs.subscribe(
  nextCallback,
  errorCallback,
  completeCallback
);

They must be passed in this order. 它们必须按此顺序传递。 You don't have to pass all three. 你不必通过这三个。 Many times only the nextCallback is implemented: 很多时候只实现了nextCallback

obs.subscribe(nextCallback);

You can add a callback function to your list of get_category(...) parameters. 您可以将回调函数添加到get_category(...)参数列表中。

Ex: 例如:

 get_categories(number, callback){
 this.http.post( url, body, {headers: headers, withCredentials:true})
    .subscribe( 
      response => {
        this.total = response.json();
        callback(); 

      }, error => {
    }
  ); 

}

And then you can just call get_category(...) like this: 然后你可以像这样调用get_category(...):

this.get_category(1, name_of_function);

You can code as a lambda expression as the third parameter(on complete) to the subscribe method. 您可以将lambda表达式编码为subscribe方法的第三个参数(完成后)。 Here I re-set the departmentModel variable to the default values. 在这里,我将departmentModel变量重新设置为默认值。

saveData(data:DepartmentModel){
  return this.ds.sendDepartmentOnSubmit(data).
  subscribe(response=>this.status=response,
   ()=>{},
   ()=>this.departmentModel={DepartmentId:0});
}
get_categories(number){
 return this.http.post( url, body, {headers: headers, withCredentials:true})
      .map(t=>  {
          this.total = t.json();
          return total;
      }).share();
  );     
}

then 然后

this.get_category(1).subscribe(t=> {
      this.callfunc();
});

You can do this be using a new Subject too: 您也可以使用新Subject

Typescript: 打字稿:

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) => {
     // ...
   }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM