很好,可能被标记为重复项,如果对不起,请注意。在没有任何适当解决方案的情况下进行了大量的谷歌搜索以查找如何实际执行此操作(尽管我不是vue专家。)

基本上..我想做的..是从api => store => vue组件传递成功还是失败。如果有错误...我将向用户显示错误代码(目前为...)

事物的方式..

1)从vue组件触发的方法。调度到$ store(modal.vue)

2)触发状态操作以设置突变类型并调用API。

3)调用Api方法。

4)返回成功或错误,以及http.statuscode...。

MODAL.VUE

doRefund: function(){
            this.$store.dispatch('doRefund', {
                    Username : this.loggedInUser.account.username,
                    OrderID: this.selectedOrder.orderid,
                    IsFeeApplied: false,
                    CreditAmount: this.refundAmount,
                    ChargeFee: 0.0,
                    Reason: "reason-not-specified",
                    Description: this.comment,
                    BearerToken: "Bearer " + this.accessToken
            })
            .then(result => {
                if(result === true){
                  alertify.success('It worked!')
                }
                else{
                    alertify.alert('There was an error, and the errorcode is' + errorcode ????)
                }
            })
        }

STORE.JS
doRefund({ commit }, refundParams){
        api.tryRefund(refundParams)
        .then(refundCompleted => {
            commit(types.SET_REFUND_COMPLETED, true)
            return true;
        })
        .catch(err => {
            //TODO: How to i fetch, and pass the errorcode ?
            commit(types.SET_REFUND_COMPLETED, false)
            return false;

        })
    },

API.JS
tryRefund(refundParams) {
    console.log('=== try ====');
    console.log( refundParams );
    return new Promise((resolve, reject) => {
        var config = {
            headers: {
                'Content-Type': ' application/json',
                'Authorization': refundParams.BearerToken
            }
        };
        return axios.post('the-url-to-the-service', refundParams, config)
            .then(
                () => resolve(true))
            .catch( error => {
                console.log('=== ERROR ====');
                console.log( error.response );

            })
    });
}

最佳答案

您需要在error.response文件的reject方法中将tryRefund传递给api.js处理程序:

.catch(error => {
  console.log('=== ERROR ====');
  console.log( error.response );
  reject(error)
})

然后,您应该在doRefund操作方法中抛出错误:
.catch(err => {
  //TODO: How to i fetch, and pass the errorcode ?
  commit(types.SET_REFUND_COMPLETED, false)
  throw err;
})

然后将其捕获到catch方法的$dispatch处理程序中:
this.$store.dispatch('doRefund', {
  ...
})
.then(result => {
  ...
})
.catch(error => {
  console.log(error); // this is the error you want
})

关于vue.js - VUE和Axios API:将错误代码从api传递到存储到vue组件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46533084/

10-16 12:39