HTTP 请求响应后获取值

Getting value after HTTP request response

我有这个工作

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() return 数据并将其传送到 add() 并进一步处理的方法是什么)

private result;

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

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

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

}

Return Observable 来自 findtest 方法并订阅它以获得您的回复。

findTest(name: string) {
  return this.http.get<HttpResponse<any>>(destination, options);
}

add() {
  this.findTest(this.name).subscribe(res => {
      console.log(res);
   });
 }

这种情况用services比较好。将 findTest 放入服务文件并从您的组件订阅它。