Destabilizator
Destabilizator

Reputation: 495

Getting value after HTTP request response

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)

Upvotes: 0

Views: 1341

Answers (3)

uiTeam324
uiTeam324

Reputation: 1245

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.

Upvotes: 1

Wahab Shah
Wahab Shah

Reputation: 2256

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

}

Upvotes: 0

Lyczos
Lyczos

Reputation: 316

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.

Upvotes: 0

Related Questions