Sending Object through HTTP POST in Angular

Im creating a Web App using angular. Right now, my project already have a backend, a frontend and a API Rest. In this case, im trying to send an object from my page in the frontend to the service of the frontend, like this:

  async save_pack(index: any){
    await this.usuarioService.save_pack(this.packs[index])
      .then((data) => {
        console.log(JSON.stringify(data));
      })
      .catch(err => alert(err));
  }

then, I use the HTTP POST to send that object from the service to the API Rest like this:

   save_pack(Pack: any){
    return this.http
      .post("http://localhost:8000/save_pack",Pack)
      .toPromise()
  }

My function in the API Rest is this:

app.post('/save_pack', async (req,res) => {
    console.log("Elementos de la respuesta: " + req.body)
    //const Pack = req.body.Pack;

    let result = await save_pack(Pack);
    res.send(result)
    return res;
})

However, when I tried to check if the object was correctly passed, I realised that it is not properly passed as I doesn´t show it values (I get Elementos de la respuesta: undefined). I guess im doing it wrong, but I can´t figure out how to do it, because I am new in Angular. Any idea?

Upvotes: 0

Views: 5342

Answers (2)

Dario
Dario

Reputation: 394

from the documentation

The HttpClient service makes use of observables for all transactions. You must import the RxJS observable and operator symbols that appear in the example snippets. These ConfigService imports are typical.

this one:

save_pack(Pack: any){
    return new Promise((resolve, reject) =>{
      this.http
        .post("http://localhost:8000/save_pack",Pack)
        .subscribe(res => {
            resolve(res);
          },
          (err: any) => {
            reject(err);
          }
        )
    });
  }

should be:

save_pack(Pack: any){
    return this.http
        .post("http://localhost:8000/save_pack",Pack)
        .toPromise
    });
  }

and then you can do something like this:

this.save_pack.then((data) => {
        console.log(JSON.stringify(data));
      })
      .catch((error) => {
        console.log("Promise rejected with " + JSON.stringify(error));
      });

i'm working on angular since 5 month, so i'm not really expert but i can tell you a thing: learn well observables, and use promise adn async/await pattern only if you cant do otherwise, for the rest the observables with rxjs and a state managment, like ngrx(reactive programming pattern & redux patterm) cover almost all use cases, and are very powerfull. good coding!

Upvotes: 1

pulkitjpatel
pulkitjpatel

Reputation: 46

You should make use of Observables rather than promises as Observables are well supported throughout the Angular.

So your HTTP POST method should be like this

save_pack(Pack: any): Observable<any> {
    return this.http.post("http://localhost:8000/save_pack",Pack);
  }

And then you should subscribe to this Observable in your component

save_pack(index: any) {
    this.usuarioService.save_pack(this.packs[index])
      .subscribe(resp => {
        console.log('resp');
      });      
  }

Upvotes: 0

Related Questions