Angular 7 - toPromise returns no error

Asked

Viewed 360 times

1

I’m using the Httpclient as below. However even with error 404 to toPrimise() gets into the .then() instead of .catch().

Note: Sometimes it worked with the same code. I believe it is something related to Observable be asynchronous and the Promise be synchronous.

Someone went through it ?

    import { Injectable } from '@angular/core';
    import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';

  export class LancamentoService {

     lancamentosURL = 'http://localhost:8080/lancamentos';

     constructor(private http: HttpClient) { }

     excluir(codigo: number): Promise<void> {

         let headers = new HttpHeaders();
         headers = headers.set(
            'Authorization', 
            'Basic YWRtaW5AYWxnYW1vbmV5LmNvbTphZG1pbg==');

         return this.http
           .delete(`${this.lancamentosURL}/${codigo}999`, { headers: headers } )
           .toPromise()
           .then( response => null)
           .catch(error => error);
     }
}

COMPLEMENT

After a few comments I understood that Observable and Promise are asynchronous.

Analyzing the code better after inquiries, I noticed the following: is generating the error in the service, but is not arriving in the component controller as an error.

In the controller I have the following function.

private excluir(lancamento: any) {

    this.lancamentoSevice.excluir(lancamento.codigo)
      .then(response => {
        console.log('Response 2 : ', response );
        this.grid.first = 0;
        this.pesquisar();
        this.messageService.add({
          severity: 'success',
          summary: 'Sucesso',
          detail: 'Sucesso ao Excluir o lançamento : ' + lancamento.codigo });
      })
      .catch(erro => {
        console.log('erro 2: ', erro );
        this.errorHandlerService.handle(erro); } )    ;
  }

In service (this.lancamentoSevice) the function below, which is the same described initially in this post, but with a console.log for verification

excluir(codigo: number): Promise<void> {
    let headers = new HttpHeaders();
    headers = headers.set('Authorization', 'Basic YWRtaW5AYWxnYW1vbmV5LmNvbTphZG1pbg==');

    return this.http
      .delete(`${this.lancamentosURL}/${codigo}999`,  { headers: headers } )
      .toPromise()
      .then( response => {console.log('response: ' , response); return response; } )
      .catch(error => {console.log('error: ' , error); return error; });

  } 

In the delete function from the service, falls in the .catch returning the following error:

HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "OK", url: "http://localhost:8080/lancamentos/8999", ok: false, …}

However, when returning the controller’s delete function, it falls on .then instead of .catch

It was at this point that I failed to evolve.

1 answer

1

Both are asynchronous, the error may be the way the API value is returning, for example the Content-Type.

  • Any suggestions as to how I can resolve?

  • What is returning within the function? When successful?

  • I’ll see right through the night what returns and put here.

  • I posted an add-on. If you can take a look I’d appreciate it.

  • 1

    I’m not sure, but I think the problem is because the error exists in the observable that makes the request for the API, but when you receive it in the Component and turns into Promise, it is no longer a mistake. It just goes. You could try not to use toPromise (subscribe) and continue with observable that in the case of Angular is best used.

Browser other questions tagged

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