我正在尝试使用Vuex在我的VueJS应用程序中构建我的API服务。我正在重构某些东西以集中处理错误,清理等问题。我遇到的问题是通过函数调用正确地链接了Promises。
在根级别,我有一个BaseService类,该类仅使用AXIOS(不是完整类)发出API请求:
export abstract class BaseService {
protected readonly API: AxiosInstance; // Full init left out
protected deleteItem(url: string): Promise<any> {
return new Promise((resolve, reject) => {
this.API.delete(url)
.then((response: any) => {
resolve(response);
})
.catch((error: any) => {
this.handleError(error); // Local function that logs error
reject(error);
});
});
}
}
然后我在其上一层,通过组合请求URL和处理数据来管理API的不同功能:
class CompanyService extends BaseService {
private constructor() {
super();
}
public delete(id: number): Promise<any> {
return this.deleteItem(`${this.baseUrl}/api/companies/${id}`);
}
}
然后在我的Vuex动作中,我调用companyService删除函数:
const action = {
COMPANY_DELETE(context: any, id: number) {
return new Promise((resolve, reject) => {
companyService // Instance of CompanyService
.delete(id)
.then((response: any) => {
console.log(response); // This logs successfully
resolve(response);
})
.catch((error: any) => {
console.log(error); // This logs successfully
reject(error);
});
});
}
};
如我的评论所示,两个控制台日志已成功完成。当我到达调用此操作的组件时,就会出现此问题:
this.$store
.dispatch("company/COMPANY_DELETE", company.id) // Namespaced
.then((response: any) => {
console.log(response); // Never gets called
})
.catch((error: any) => {
console.log(error); // Never gets called
});
从不调用这两个控制台日志。我在这里做什么错了?
答案 0 :(得分:1)
使用axios演示动作的小示例,无需额外的承诺包装...
const store = new Vuex.Store({
state: {
followers: 0
},
mutations: {
updateFollowers(state, followers){
state.followers = followers;
}
},
actions: {
getFollowers({commit}) {
return axios.get('https://api.github.com/users/octocat').then( (response) => {
commit("updateFollowers", response.data.followers);
return "success!!!";
});
}
}
})
Vue.component('followers', {
template: '<div>Followers: {{ computedFollowers }}</div>',
created () {
this.$store.dispatch('getFollowers').then( (result) => {
console.log(result);
});
},
computed: {
computedFollowers() {
return store.state.followers;
}
}
});
const app = new Vue({
store,
el: '#app'
})
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vuex"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id="app">
<followers></followers>
</div>
答案 1 :(得分:0)
最终工作是删除Void Ray所说的多余的Promise。但是,在我的特定用例中,我还需要支持错误传播。因此,以下操作包含我需要进行的修复。
const action = {
COMPANY_DELETE(context: any, id: number) {
return companyService // Instance of CompanyService
.delete(id)
.then((response: any) => {
console.log(response);
})
.catch((error: any) => {
console.log(error);
throw error; // Needed to continue propagating the error
});
},
};