Home > Back-end >  How to map values from Backend Nest JS to Frontend Angular?
How to map values from Backend Nest JS to Frontend Angular?

Time:04-22

Backend Nest JS Service Code:

async show(): Promise<any> {
  var response: dto = new dto();
  var data = await this.sequelize.query('Exec API_Select',
    {
      type: sequelize.QueryTypes.SELECT
    });
    if(data.length>0){
       data.map((item:any) =>  {  
        
        response.foo1=item.foo1;
        response.foo2=item.foo2;
        response.foo3=item.foo3;

       });
    return response;
    }
}

Frontend Angular Code (Service):

getdata(){
  const headers = new HttpHeaders().set('Content-Type', 'application/json').set('Authorization','Bearer' ' ' token);



this.http.post<interface1>('http://localhost:3000/getdata/',null,{headers})
    .pipe(map(data => ({
      foo1:data.foo1,
      foo2:data.foo2,
      foo3:data.foo3
    })))
    .subscribe(foo => console.log(foo))
}

Now if I give dummy values in e.g. data.foo1 then it works (which means that the service and component code in Angular is fine. The Backend is also working fine since I can fetch data in Postman. The only problem is with mapping data from Backend to Frontend.

I have tried .subscribe instead of .map but it doesn't work. I have also tried it without <interface1> but still the result is same.

I am a beginner in this field and new to Nest JS and Angular. Please have a look. Thankyou.

Edit:

return this.http.post('http://localhost:3000/getdata/',null,{headers}).subscribe(data => {
     this.dataout = data});

If I fetch the values as a single variable, e.g. in the above code, data is fetched, and in the Backend there is a variable data. then it also works fine. The only problem is with mapping.

API response from Postman:

{
    "statusCode": 200,
    "isSuccess": true,
    "message": "ok",
    "data": [
        {
            "foo1": 3,
            "foo2": "abc",
            "foo3": "def",
 
        },
        {
            "foo1": 1,
            "foo2": "ghi",
            "foo3": "jkl",

        }
    ]
}

CodePudding user response:

Use the correct syntax of your response

this.http
  .post<interface1>('http://localhost:3000/getdata/',null,{headers})
    .pipe(map(({ data }) => ({
      foo1:data.foo1,
      foo2:data.foo2,
      foo3:data.foo3
    })))
    .subscribe(foo => console.log(foo))
}
  • Related