问题
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