简体   繁体   English

在Vue.js中使用axios并使用单独的服务?

[英]Using axios in Vue.js with separate service?

I wanted to move axios request logic to separate service in my Vue.js app. 我想在我的Vue.js应用程序中移动axios请求逻辑来分离服务。 Axios always returns promise, how can I fetch response data from it in my component? Axios总是返回promise,如何从组件中获取响应数据? Or may be there are some other solution for this? 或者可能还有其他一些解决方案吗?

UserService.js 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();

You 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. 因为我们不是要求.then在爱可信的结果,承诺将不会得到解决。 Instead, the promise itself will be returned from this method. 相反,promise本身将从此方法返回。 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 combine async actions with the state manager for better control. 但是,如果您使用的是vuex或redux等状态管理解决方案,则可以将异步操作与状态管理器结合使用,以便更好地控制。 If you are using redux, you can use redux thunk or redux-saga helper libraries. 如果您使用的是redux,则可以使用redux thunk或redux-saga帮助程序库。 If you are using vuex, you can handle such side effects in the actions (see here https://vuex.vuejs.org/en/actions.html ) 如果您使用的是vuex,则可以在操作中处理此类副作用(请参阅此处https://vuex.vuejs.org/en/actions.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM