Http request returns Zoneawarepromise

Asked

Viewed 103 times

0

I created a service to run GET / POST / DELETE and PUT solitaire. When I make the first request I get Zoneawarepromise in the body of the message. How to access data within Zoneawarepromise or change my code to not return Zoneawarepromise?

inserir a descrição da imagem aqui

Below the GET within the service

  public get(url: string) {
    const header = this.createHeader();

    return new Promise(async(resolve) => {
      try {
        const result = this._HttpClient.get(url, { headers: header }).toPromise();
        resolve({ success: true, data: result, error: undefined });
      } catch (error) {
        resolve({ success: false, data: {}, error });
      }
    }); 
  }

Here’s my request inside the Component.

this._HttpService.get(`${ServerUrl.ApiUrl}MarkingGet`).then(data => console.log(data));
  • I don’t understand, because it involved the get in a Promise? Alíás should go in the documentation of Angular and see how does a service get and how consumes, has nothing to do with it there. Just to get an idea Angular uses Observables and for the call of the method uses subscribe.

  • @Leandrade the idea is to create a service and decrease the amount of repeated codes. But anyway I will do a read in the documentation

1 answer

0

I found a document explaining how to make the request, very good for beginners like me.

https://www.techiediaries.com/angular/angular-9-8-tutorial-by-example-rest-crud-apis-http-get-requests-with-httpclient/

In service

 handleError(error: HttpErrorResponse) {
        let errorMessage = 'Unknown error!';
        if (error.error instanceof ErrorEvent) {
          // Client-side errors
          errorMessage = `Error client: ${error.error.message}`;
        } else {
          // Server-side errors
          errorMessage = `Error server: ${error.status}\nMessage: ${error.message}`;
        }
        window.alert(errorMessage);
        return throwError(errorMessage);
}    

 public get(url: string) {
   const header = this.createHeader();
    
   return this._HttpClient.get(url, { headers: header }).pipe(catchError(this.handleError));
 }

In the component

this._HttpService.get(`${ServerUrl.ApiUrl}MarkingGet`).subscribe(data => {
   this.result = data;

   console.log(this.result);
})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.