admin管理员组文章数量:1327945
I wanted to move axios request logic to separate service in my Vue.js app. Axios always returns promise, how can I fetch response data from it in my ponent? Or may be there are some other solution for this?
UserService.js
class UserService {
getUser() {
const token = localStorage.getItem('token');
return axios.get('/api/user', {
headers: {
'Authorization': 'Bearer ' + token
}
}).then(function (response) {
return response.data;
}).catch(function (error) {
console.log(error);
});
}
getUserTasks() {
const token = localStorage.getItem('token');
return axios.get('/api/user/task', {
headers: {
'Authorization': 'Bearer ' + token
}
}).then(response => {
return response;
}).catch(function (error) {
console.log(error);
});
}
get currentUser() {
return this.getUser();
}
}
export default new UserService();
I wanted to move axios request logic to separate service in my Vue.js app. Axios always returns promise, how can I fetch response data from it in my ponent? Or may be there are some other solution for this?
UserService.js
class UserService {
getUser() {
const token = localStorage.getItem('token');
return axios.get('/api/user', {
headers: {
'Authorization': 'Bearer ' + token
}
}).then(function (response) {
return response.data;
}).catch(function (error) {
console.log(error);
});
}
getUserTasks() {
const token = localStorage.getItem('token');
return axios.get('/api/user/task', {
headers: {
'Authorization': 'Bearer ' + token
}
}).then(response => {
return response;
}).catch(function (error) {
console.log(error);
});
}
get currentUser() {
return this.getUser();
}
}
export default new UserService();
Share
Improve this question
asked Jan 27, 2018 at 13:54
Nick SynevNick Synev
3874 silver badges11 bronze badges
1 Answer
Reset to default 7You can return the promise from the request module and use it anywhere. For example,
sendGet(url) {
const token = localStorage.getItem('token');
return axios.get(url, {
headers: {
'Authorization': 'Bearer ' + token
}
})
}
Since we are not calling .then
on the axios result, the promise will not be resolved. Instead, the promise itself will be returned from this method. Thus it can be used as follows,
getUser() {
axiosWrapper.sendGet('/api/user')
.then((response)=> {
// handle response
})
.catch((err)=>{
// handle error
})
}
However, if you are using a state management solution like vuex or redux, you can bine async actions with the state manager for better control. If you are using redux, you can use redux thunk or redux-saga helper libraries. If you are using vuex, you can handle such side effects in the actions (see here https://vuex.vuejs/en/actions.html)
本文标签: javascriptUsing axios in Vuejs with separate serviceStack Overflow
版权声明:本文标题:javascript - Using axios in Vue.js with separate service? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742224176a2435733.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论