ngOnInIt函数中如何在Angular8 firestore中使用Async?

时间:2019-10-01 12:44:36

标签: javascript angular firebase asynchronous google-cloud-firestore

我正在ngOnInIt函数中从firestore检索数据,并尝试在同一生命周期中使用该数据。如何使用Async解决问题?

>=

由于函数不等待接收快照更改,因此我收到的userList []空数组。

2 个答案:

答案 0 :(得分: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();
  }

答案 1 :(得分:0)

使用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);
}