0

I have this working

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

Which works, because the response gets printed to console after it arrives. I don't understand how to work with this, so I can do eg.

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

(basically, what's the way to make findTest() return data and get those to add() and process further)

2
  • Http calls are asynchronous, so your function cannot directly return the value. It should return the Observable so you can subscribe to it in your calling function. Commented Aug 6, 2020 at 10:18
  • Ye, that's what I'm trying to understand, how to work with this asynchronicity Commented Aug 6, 2020 at 11:53

3 Answers 3

1

Return Observable from findtest method and subscribe it to get your response.

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

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

It's better to use services in this kind of situation. Put findTest in service file and subscribe it from your component.

Sign up to request clarification or add additional context in comments.

Comments

0
private result;

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

after that result will be in the result variable.

Comments

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

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.