Angular 6 subscribe

Asked

Viewed 40 times

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

  • @Eduardogonçalves, I did according to your orientation and continues displaying.

  • Because the console.log is executed before the callback of the subscribe

  • @Eduardogonçalves, I edited the code.

  • 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()

  • 1

    @Eduardogonçalves, now it worked, I understood how it works. Thank you!

Show 1 more comment
No answers

Browser other questions tagged

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