Angular Firestore文档更新导致订阅中的无限循环

时间:2019-01-06 07:33:59

标签: firebase rxjs angularfire2

我了解此问题,但无法解决。我正在查询特定文档以提取令牌字符串数组。我需要在此字符串的末尾附加一个新令牌,然后使用此新令牌数组更新当前文档。

为此,我订阅了一个查询,然后在其中更新了该文档。但是,当然,当您更新同一对象时,订阅将再次运行,从而创建无限循环。我尝试合并一个take(1)管道rxjs运算符,但没有任何改变。有什么建议吗?

这是我的代码:

this.afs.collection('users').doc(user.userUID).valueChanges().pipe(take(1)).subscribe((user: userModel) => {
    const currentTokens: string[] = user.notifTokens ? user.notifTokens : [];

    //token variable is provided outside this query
    currentTokens.push(token);

    //this next lines causes the subscription to trigger again
    userRef.doc(user.userUID).update({notifTokens: currentTokens})
  })

1 个答案:

答案 0 :(得分:0)

I would recommend you avoid using a subscription in this situation, for exactly this reason. I realize the Angularfire2 docs don't list this method, but the base Firebase package includes a .get() method... and while the AF2 docs don't mention the .get() method... the source code shows that it is supported.

Try something like:

this.afs.collection('users').doc(user.userUID).get().then( (user: userModel) => {
    if (user.exists) {
        console.log("Document data:", user.data());

        // Do stuff with the info you get back here

        const currentTokens: string[] = user.data().notifTokens ? user.data().notifTokens : [];
        currentTokens.push(token);
        userRef.doc(user.data().userUID).update({notifTokens: currentTokens})

    } else {
        // user.data() will be undefined in this case
        console.log("No such document!");
    }
}).catch(function(error) {
    console.log("Error getting document:", error);
});
相关问题