我正在尝试使用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 delete函数:
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
});
永远不会调用这两个控制台日志。我在这里做错了什么?
最佳答案
展示axios Action 的小示例,无需额外的 promise 包装。
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>