Angular - wait for this variable to have value and then execute

霸气de小男生 提交于 2021-02-10 14:13:45

问题


In ngOnInit(), first line of code fetches the value from local storage and then that value is used to filter data from database.

Both executes together and I don't get the result. How can I do something like the second function waits for the first one to get value.

Below is my ts code:

 ngOnInit() {

    //get id of user
    this.storage.get('loggedInUser').then((val) => {
      console.log('Your user ID is', val);
      this.loggedInusr = val;
    });

    firebase.firestore().collection(`todos`)
  .where("assignTo", "==", this.loggedInusr) // don't get value here, if I hard code all works
  .get()
  .then(querySnapshot => {
      querySnapshot.forEach(function(doc) {
          console.log("assignTo");
          console.log(doc.id, " ===> ", doc.data());
      });
    });

    ...

回答1:


You could move the 2nd procedure inside the handling of 1st procedure. Try the following

ngOnInit() {
  //get id of user
  this.storage.get('loggedInUser').then((val) => {
    console.log('Your user ID is', val);
    this.loggedInusr = val;

    firebase.firestore().collection(`todos`)
      .where("assignTo", "==", this.loggedInusr) // dont get value here, if i hard code all works
      .get()
      .then(querySnapshot => {
        querySnapshot.forEach(function(doc) {
            console.log("assignTo");
            console.log(doc.id, " ===> ", doc.data());
        });
      });

  });
  .
  .
}



回答2:


you can use rxjs switch map for that, then if any values change in observable this will update automatically

import { from } from 'rxjs';

     from(this.storage.get('loggedInUser'))
      .pipe(switchMap((loggedUser) => 
              from(firebase.firestore().collection(`todos`).where("assignTo", "==",loggedInusr) .get()).subscribe(querySnapshot => {
                querySnapshot.forEach(function(doc) {
                console.log("assignTo");
                console.log(doc.id, " ===> ", doc.data());
            });
    ))


来源:https://stackoverflow.com/questions/60898341/angular-wait-for-this-variable-to-have-value-and-then-execute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!