【问题标题】:How to use Async with Angular8 firestore in ngOnInIt function?如何在 ngOnInIt 函数中使用 Async 和 Angular8 firestore?
【发布时间】:2020-01-30 18:16:13
【问题描述】:
我正在 ngOnInIt 函数中从 firestore 检索数据,并尝试在同一生命周期中使用该数据。如何使用 Async 解决问题?
ngOnInit() {
this.service.getUserData().subscribe(actionArray =>{
this.userList = actionArray.map(item =>{
console.log("Items", item);
console.log("Data : ", item.payload.doc.data());
return {
id : item.payload.doc.id,
...item.payload.doc.data()
} as customersUser;
})
});
console.log("User List : ", this.userList);
this.getUserData();
}
getUserData(){
this.userList.map(item =>{
if(item.id == this.userId){
this.userObj = item;
}
})
console.log(this.userObj);
}
我收到一个空的 userList[] 数组,因为该函数不等待接收快照更改。
【问题讨论】:
标签:
javascript
angular
firebase
asynchronous
google-cloud-firestore
【解决方案1】:
使用async await。这是另一种解决方案。试试看。
async ngOnInit() {
await this.service.getUserData().subscribe(actionArray =>{
this.userList = actionArray.map(item =>{
console.log("Items", item);
console.log("Data : ", item.payload.doc.data());
return {
id : item.payload.doc.id,
...item.payload.doc.data()
} as customersUser;
})
});
console.log("User List : ", this.userList);
await this.getUserData();
}
getUserData(){
this.userList.map(item =>{
if(item.id == this.userId){
this.userObj = item;
}
})
console.log(this.userObj);
}
【解决方案2】:
移动这条线
console.log("User List : ", this.userList);
到userList 填充数据的位置,即订阅者内部。所以,而不是
ngOnInit() {
this.service.getUserData().subscribe(actionArray =>{
this.userList = actionArray.map(aMappingFunction);
});
console.log("User List : ", this.userList);
this.getUserData();
}
做
ngOnInit() {
this.service.getUserData().subscribe(actionArray =>{
this.userList = actionArray.map(aMappingFunction);
console.log("User List : ", this.userList);
});
this.getUserData();
}