Suppose I want to hide the work with HttpClient behind the service, and then inject it into a specific component and pull methods so that all the details are hidden from the component.

The problem is asynchronous HttpClient . For example, I pull get and the method flies farther, returning undefined .

Well, for example, the component accesses the service service.GetCars (), which pulls the API inside itself and sends a get request, how can I get this data inside the component?

Should I return Observable, and the user of this service execute subscribe and remap the data? Well, in my opinion it is not quite right.

  • the question is incomprehensible - overthesanity
  • How to properly wait for the query and return the requested data to the component, which can then be used for display - iluxa1810 10:02 pm
  • Well, it turns out sabsribytsya outside ... - iluxa1810
  • You did not attach a single piece of code, you want to be guessing here on the coffee grounds? :) - overthesanity

1 answer 1

use code:

 this.service.GetData().subscribe(res => { console.log(res); //res - полученные данные }); 

service code:

 import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class AuthorizeService { constructor(private http: HttpClient) { } GetData(){ return this.http.get('https://localhost:44397/api/GetData'); } }