Httpclient POST request with Angular 7 returning Undefined

Asked

Viewed 475 times

2

all right? I’m having trouble making http requests on my Angular CLI project.

When I use this.http.post(url, dados, config).subscribe(ret => this.retorno = ret) and then I give console.log(this.retorno) he returns Undefined.

I think it’s something about "asynchrony," because if I put a SetTimeout() in this.log console it shows the correct post return.

Do I have to do any treatment on that requisition? What I can do to ensure that execution will only continue when this request is completed?

I spent a whole day looking around, nowhere have I seen special treatment in these requisitions, something so simple that I’m wasting a lot of time, I’m already going crazy with this.

2 answers

1

Hello, when you subscribe, it makes the call and waits for the return to run the code inside the subscribe, but releases the program to run the following lines, ie it runs your console.log(this.return) before feeding the variable this.return.

The code below is just an example based on your question, it will print on the console, first the phrase 'good morning' and then your return;

    this.http.post(url, dados, config).subscribe(ret => {
        this.retorno = ret; 
        console.log(this.retorno);
    });
    console.log('bom dia');

  • Thanks Edgar, I have to get used to these asynchronous requisitions.

-1


You can do it this way :

async minhaFuncao() { 
  this.retorno = await this.http.post(`url`, dados, config).toPromise()
  console.log(this.retorno)
}
  • 1

    That’s how it worked. Meaning that whenever I depend on the result of a request to do something I will have to use async and await.

Browser other questions tagged

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