【问题标题】:Getting value after HTTP request response在 HTTP 请求响应后获取值
【发布时间】:2020-11-26 14:03:05
【问题描述】:

我有这个工作

findTest(name: string) {
  this.http.get<HttpResponse<any>>(destination, options).subscribe(data => {
    console.log(data);
});

这很有效,因为响应在到达后会打印到控制台。 我不明白如何使用它,所以我可以这样做。

add() {
    const check = this.testsService.findTest(this.name);
    console.log(check);
}

(基本上,有什么方法可以让findTest() 返回数据并将这些数据发送到add() 并进一步处理)

【问题讨论】:

  • Http 调用是异步的,所以你的函数不能直接返回值。它应该返回Observable,以便您可以在调用函数中订阅它。
  • 是的,这就是我想要理解的,如何处理这种异步性

标签: angular typescript http-get


【解决方案1】:
private result;

add() {
  const check = this.testsService.findTest(this.name);
  check.subscribe(response => this.result = response); // don't forget to unsubscribe 
}

之后,结果将在 result 变量中。

【讨论】:

    【解决方案2】:
    HTTP call will return an observable that you need to subscribe, 
    If call is successful you will get the result if not in second method error will be
    thrown and finally after the call is complete you get 3rd method (it can be used if
    you want to set your loader to false after your request is fully done etc). 
    But you can leave it empty as well. Check the following format
    
    
     add() {
       this.testsService.findTest(this.name).subscribe(
       (data: any) => {
           console.log({data});
           this.variable_To_Store_Response= data;
       },
      (err) => { console.error(err); },
      () => { },
    );
    
    }
    

    【讨论】:

      【解决方案3】:

      从 findtest 方法返回 Observable 并订阅它以获得您的回复。

      findTest(name: string) {
        return this.http.get<HttpResponse<any>>(destination, options);
      }
      
      add() {
        this.findTest(this.name).subscribe(res => {
            console.log(res);
         });
       }
      

      在这种情况下最好使用services。将findTest 放入服务文件并从您的组件中订阅它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-14
        • 1970-01-01
        • 2017-07-14
        • 1970-01-01
        • 2011-12-21
        • 2020-11-06
        相关资源
        最近更新 更多