Angular - 访问 'then' block 中的 ngrx 存储

标签 angular firebase angular6 observable ngrx

我正在使用 Angular6 和 Cloud Firestore(不是实时数据库)。我有一个服务,它包含一个函数,该函数将文档添加到集合中,然后使用 .then block 获取刚刚创建的文档的 ID,然后执行一些其他逻辑。在此函数中,我想使用 ngrx 访问我保存在 Store 中的一些购物车内容。在我的 ngOnInit 中,我有以下代码,它订阅并获取内容并将其分配给 cartContents (服务中的全局变量)。

this.myState = this.store.select('shoppingCart');
this.shoppingCartStateSubscription = this.myState.subscribe(val => {
   this.cartContents = val.basketList;
});

然后我希望能够访问 .then block 内的 this.cartContents 的值,但是,该值显示为未定义。我做错了什么/误解了什么?

函数代码:

processPayment(token: any, amount: number){
        const payment = { token, amount };

this.paymentCollection.doc(`${this.userId}`).collection('payments').add({
            payment
        })
        .then(docRef => {
            console.log("Document written with ID: ", docRef.id);
            this.docRefId = docRef.id;
            this.db.collection("payments/"+`${this.userId}`+"/payments").doc(`${this.docRefId}`)
        .onSnapshot(function(doc) {
            console.log("Current data: ", doc.data());
            if(doc.data().status === "succeeded"){

                const updatedBalance = this.balance - amount;;

                let writeBatch = firebase.firestore().batch();

                //Update purchased lessons ref
                console.log(this.cartContents); //APEARS AS UNDEFINED

                for(let buyable of this.cartContents){
                    let purchasedLessonsRef = this.afs.firestore.doc(`/purchased_lessons/${this.userId}/lessons/${buyable.b_id}`);
                    writeBatch.update(purchasedLessonsRef, buyable);
                }

                //Update balance ref
                let userBalanceRef = this.afs.firestore.doc(`/users/${this.userId}`);
                writeBatch.update(userBalanceRef, {balance: updatedBalance});

                this.docRefId = null;

                return writeBatch.commit().then(function () {
                    console.log("commiting batch")
                });
            }
        });

        console.log("finished function");
        })
    .catch(error => console.error("Error adding document: ", error))
}

最佳答案

如果您在 OnNgInit() 上获取值,我能想到的唯一原因是 this 的绑定(bind)。

怀疑是 function(doc){//stuff},将其更改为 (doc) => {//stuff}

您还可以尝试用 arrow 函数替换所有函数。

    processPayment = (token: any, amount: number) =>{
        const payment = { token, amount };

this.paymentCollection.doc(`${this.userId}`).collection('payments').add({
            payment
        })
        .then(docRef => {
            console.log("Document written with ID: ", docRef.id);
            this.docRefId = docRef.id;
            this.db.collection("payments/"+`${this.userId}`+"/payments").doc(`${this.docRefId}`)
        .onSnapshot((doc) => {
            console.log("Current data: ", doc.data());
            if(doc.data().status === "succeeded"){

                const updatedBalance = this.balance - amount;;

                let writeBatch = firebase.firestore().batch();

                //Update purchased lessons ref
                console.log(this.cartContents); //APEARS AS UNDEFINED

                for(let buyable of this.cartContents){
                    let purchasedLessonsRef = this.afs.firestore.doc(`/purchased_lessons/${this.userId}/lessons/${buyable.b_id}`);
                    writeBatch.update(purchasedLessonsRef, buyable);
                }

                //Update balance ref
                let userBalanceRef = this.afs.firestore.doc(`/users/${this.userId}`);
                writeBatch.update(userBalanceRef, {balance: updatedBalance});

                this.docRefId = null;

                return writeBatch.commit().then(() => {
                    console.log("commiting batch")
                });
            }
        });

        console.log("finished function");
        })
    .catch(error => console.error("Error adding document: ", error))
}
    }

另一种选择是显式绑定(bind)它,例如:

.snapshot(function(doc){
//function body
}).bind(this) // this is binding the correct context (this) to the function

关于Angular - 访问 'then' block 中的 ngrx 存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53889728/

相关文章:

javascript - 等待 Angular 5 中的 *ngIf 之后元素渲染?

javascript - InAppBrowser 应使用后台线程警告

android - Firebase pyfcm 发送带有图像的推送通知

angular - 如何在 FormArray( react 形式)中使用 mat-autocomplete(Angular Material Autocomplete)

Angular 6 - 函数未定义

javascript - 如何以编程方式将 ngBootstrap 弹出窗口添加到元素?

Angular 日期时间选择器?

尝试更改组件时出现 Angular 6+ 路由问题

java - 如何从 Firebase 数据添加 Google map 标记?

javascript - 在 Angular 7 中设置 sass 变量值