I'm making a post request, I put the variable this.metodo=res, but when I put console.log(this.metodo) or try to use the filter it returns undefined
ngOnInit(): void {
this.cartS.getTransporteMetodo(this.storeS.layout.emp.id).subscribe((res: any[]) => {
this.metodo = res;
});
console.log(this.metodo)
filterMetodos(){
return this.metodo.filter( metodos => metodos.nome );
}
the json
{
"id": 1,
"emp_id": 1,
"nome": "Retirada na Loja",
"tipo": "RETIRA",
"subtipo": null,
"latLng": [-25.45264, -49.26653],
"vFreteMin": 0,
"vFreteGratis": null,
"periodos": [
{
"id": 8,
"transporte_id": 1,
"ativo": 1,
"periodo": "Comercial (das 8h \u00e0s 19h)",
"corte": "17:00",
"data": null,
"week": []
}
]
},
getTransporteMetodo(empId){
return this.http.post(environment.API_URL 'transporte/getAll', { empId });
}
CodePudding user response:
The reason of getting undefined is that the method is asnyc. So you try to access the variable before being inicialized. If you want to filter the response put the filter into the subscribe method.
sometihng like this:
this.cartS.getTransporteMetodo(this.storeS.layout.emp.id).subscribe((res: any[]) => {
this.metodo = res.filter(item=>nome);
});
CodePudding user response:
Move your log inside the the subscribe callback
this.cartS.getTransporteMetodo(this.storeS.layout.emp.id).subscribe((res: any[]) => {
this.metodo = res;
console.log(this.metodo)
});