我使用的是 Angular 版本 11 我正在访问服务的函数以从 API 获取所有数据并将其显示在我使用控件 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:) 中打印一个空数组 如何让客户始终拥有数据?
答案 0 :(得分:0)
你没有丢失任何东西。这就是异步代码的工作原理。搜索以了解 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
首先尝试理解异步代码流的这个概念。