1
Console.log return Undefined
I have the following code snippet:
Service:
constructor(private http: HttpClient) { }
getCentrosCustos() {
return this.http.get<CentroCusto[]>(API);
}
Component:
centrosCustos: any;
ngOnInit(): void {
this.centroCustoService.getCentrosCustos().subscribe(dados => {
this.centrosCustos = dados;
console.log(this.centrosCustos);
});
}
Your log console needs to be placed inside the subscribe instruction, as it is an asynchronous function, at the time of the log console, its variable has not been completed yet
– Eduardo Gonçalves
@Eduardogonçalves, I did according to your orientation and continues displaying.
– user150504
Because the
console.log
is executed before the callback of thesubscribe
– Costamilam
@Eduardogonçalves, I edited the code.
– user150504
If Voce logs the console into data, the result is correct ? Because your code is correct now, it may actually be Undefined your return from the getCentrosCustos function()
– Eduardo Gonçalves
@Eduardogonçalves, now it worked, I understood how it works. Thank you!
– user150504