【问题标题】:Function loses all data [duplicate]函数丢失所有数据[重复]
【发布时间】:2021-08-03 02:13:50
【问题描述】:

我正在使用 Angular 版本 11 我正在访问服务的功能以从 API 获取所有数据并将其显示在我使用 control ng generate @angular/material:table

创建的表中

客户端模型

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
}

客户服务

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

客户表

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
  }

对于我正在打印的值,第一个 console.log (Date:) 打印我在数据库中的所有数据,但在第二个 (Clients:) 中打印一个空数组 如何让客户始终拥有数据?

【问题讨论】:

    标签: javascript node.js arrays angular typescript


    【解决方案1】:

    你没有丢失任何东西。这就是异步代码的工作方式。搜索以了解 subscribe 方法的异步工作方式。

      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
      }
    

    代码流程是

    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 
    

    所以通常你会在控制台中看到打印出来的

    hey1
    hey3
    hey2
    

    首先尝试理解异步代码流的这个概念。

    【讨论】:

      猜你喜欢
      • 2021-10-16
      • 2012-03-25
      • 2013-02-16
      • 2012-10-04
      • 2016-09-08
      • 1970-01-01
      • 1970-01-01
      • 2020-06-10
      相关资源
      最近更新 更多