简体   繁体   中英

How to use Async with Angular8 firestore in ngOnInIt function?

I am retrieving data from firestore in the ngOnInIt function and trying to use that data in that same lifecycle. How to use Async to solve the problem?

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

I am receiving an empty array of userList[] since the function does not wait to receive snapshot changes.

Move this line

    console.log("User List : ", this.userList);

to where the userList is populated with data, that is, inside the subscriber. So, instead of

ngOnInit() {
    this.service.getUserData().subscribe(actionArray =>{
        this.userList = actionArray.map(aMappingFunction);
    });
    console.log("User List : ", this.userList);

    this.getUserData();
  }

do

ngOnInit() {
    this.service.getUserData().subscribe(actionArray =>{
        this.userList = actionArray.map(aMappingFunction);
        console.log("User List : ", this.userList);
    });

    this.getUserData();
  }

Use async await . It's another solution. try it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM