0

i´m using angular version 11 I'm accessing a function of a service to get all the data from an API and show it in a table I created using the control ng generate @angular/material:table

Client Model

export interface Client {
    id?: number,
    Codigo: string,
    Nome: string,
    Contribuinte?: number,
    Morada1?: string,
    Morada2?: string,
    Localidade?: string,
    CodigoPostal?: string,
    LocalidadeCP?: string,
    Contacto?: number,
    Telefone: number,
    EMail: string,
    Observacoes?: string
}

Client Service

read(): Observable<Client[]>{
    return this.http.get<Client[]>(this.baseUrl).pipe(
      catchError(e => this.handelError(e))
      )
  }

Client table

clients: Client[] = []               
  
...


constructor(private client: ClientService) {
    super();
  }
...

  getData(): Client[] {
    this.client.read().subscribe(
      data => {
        this.clients = data
        console.log("Data: ", this.clients)
      })
      console.log("Clientes: ", this.clients)
      return this.clients
  }

For the values I'm printing, the first console.log (Date:) prints all the data I have in the database but in the second (Clients:) prints an empty array How can I make clients always have the data?

1 Answers1

0

You didn't loose anything. It is how asynchronous code works. Search to understand the asynchronous way subscribe method works.

  getData(): Client[] {
    this.client.read().subscribe(
      data => {
        this.clients = data 
        console.log("Data: ", this.clients) <---This part of the code is invoked after the other line that I describe under. This block of code here is executed asynchronously only when the call to this.client.read returns 
      })
      console.log("Clientes: ", this.clients) <--This is out of subscription so it executes first before the call with this.client.read has returned
      return this.clients
  }

The code flow is

console.log("hey1"); <-- this line executes first

this.client.read().subscribe(data => { console.log("hey 2"); } );   <--call is invoked but the block of code does not execute now

console.log("hey3") <-- since the previous call needs some time to return results, this line of code here is executed now

// If some time later the call has returned the block of { console.log("hey 2"); } is executed, when the call has returned 

So normally you will see in the console printed

hey1
hey3
hey2

First try to understand this concept of the asynchronous code flow.

Panagiotis Bougioukos
  • 15,955
  • 2
  • 30
  • 47