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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42238819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:00:09  来源:igfitidea点击:

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

javascriptangulartypescriptpromisesubscribe

提问by Louise

I need to call a method after get the data from the http post request

我需要在从 http post 请求中获取数据后调用一个方法

service: request.service.TS

服务: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

服务: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);like this

但是我需要像这样send_catagories()调用后调用组件内部的方法this.get_categories(1);

component: categories.TS

组件:categories.TS

search_categories() {

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

What I doing wrong?

我做错了什么?

回答by AngularChef

Update your get_categories()method to returnthe total (wrapped in an observable):

更新您的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());
}

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(),您可以订阅由返回的 observable 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的方法都接受 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 nextCallbackis implemented:

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

obs.subscribe(nextCallback);

回答by Gab

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

回答by Sushrut Kanetkar

You can code as a lambda expression as the third parameter(on complete) to the subscribe method. Here I re-set the departmentModel variable to the default values.

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

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

回答by Willi Mentzel

You can do this be using a new Subjecttoo:

你也可以使用新的来做到这一点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) => {
     // ...
   }
);

回答by pixelbits

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