Получение значения после ответа на HTTP-запрос - PullRequest
0 голосов
/ 06 августа 2020

У меня это работает

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() и обрабатывать дальше)

Ответы [ 3 ]

1 голос
/ 06 августа 2020

Верните 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 в служебный файл и подпишитесь на него из своего компонента.

0 голосов
/ 06 августа 2020
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); },
  () => { },
);

}
0 голосов
/ 06 августа 2020
private result;

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

после этого результат будет в переменной result.

...