【发布时间】:2021-01-07 22:27:00
【问题描述】:
这个问题可能与 async/await 有关,但我尝试将它们放在我的函数中的几个位置。
//this is at the top of the class
userFriends: any = [];
matches()
{
var matches = [];
this.isVisible2 = true;
this.afstore.collection("matches").valueChanges().pipe(take(1)).subscribe((val: any) => {
this.userMatches = [];
matches = [];
// this part up here is a bit ugly and i could use functions inside if statements but first i wanted to get the code working, then take care of other things
for(var i=0;i<val.length;i++)
{
if(val[i].user1 === this.user.getUID())
{
this.userMatches.push({
id: val[i].id,
likedMovies: val[i].likedMovies,
maxTurns: val[i].maxTurns,
ratedMovies: val[i].ratedMovies,
turn: val[i].turn,
turnNumber: val[i].turnNumber,
me: val[i].user1,
friend: val[i].user2
});
}
else if(val[i].user2 === this.user.getUID())
{
this.userMatches.push({
id: val[i].id,
likedMovies: val[i].likedMovies,
maxTurns: val[i].maxTurns,
ratedMovies: val[i].ratedMovies,
turn: val[i].turn,
turnNumber: val[i].turnNumber,
me: val[i].user2,
friend: val[i].user1
});
}
}
if(this.userMatches.length === 0)
{
this.isVisible2 = false;
}
else
{
//the console log here works just fine like it should
console.log(this.userMatches);
for(var i=0; i<this.userMatches.length;i++)
{
// logging here works fine aswell
console.log(this.userMatches[i]);
this.afstore.collection("users").doc(this.userMatches[i].friend).valueChanges().pipe(take(1)).subscribe((val2: any) => {
console.log(this.userMatches[i]);
this.userMatches[i].friend = val2.nickname;
//matches.push(val2.nickname);
});
}
//it also logs perfectly fine here, also it would log fine if i put it in a for and logged each object in the array individually
console.log(this.userMatches);
}
});
}
我得到的错误是ERROR TypeError: Cannot set property 'friend' of undefined,但是当它被明确定义时,我怎么能得到那个错误呢?控制台日志是正确的,这意味着 this.userMatches[i].friend 在我将其用作文档名称时未定义,但当我尝试再次设置时它未定义。
这是 console.log 结果的图像
前三个对象是当我在 for 内部执行 console.log(this.userFriends[i]) 时,最后一个是 3x undefined 在 firestore 函数内部
【问题讨论】:
标签: angular typescript ionic-framework google-cloud-firestore