当前位置:首页 > 操作系统 > Ios

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

我想在我的Vue.js应用程序中移动axios请求逻辑来分离服务. Axios总是返回promise,如何从组件中获取响应数据?或者可能还有其他一些解决方案吗?

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();

解决方法:

您可以从请求模块返回承诺并在任何地方使用它.例如,

sendGet(url) {
    const token = localStorage.getItem('token');
    return axios.get(url, {
        headers: {
            'Authorization': 'Bearer ' + token
        }
    })
}

既然我们没有在axios结果上调用.那么承诺将无法解决.相反,promise本身将从此方法返回.因此它可以如下使用,

getUser() {
  axiosWrapper.sendGet('/api/user')
    .then((response)=> {
        // handle response
    })
    .catch((err)=>{
        // handle error
    })
}

但是,如果您使用的是vuex或redux等状态管理解决方案,则可以将异步操作与状态管理器结合使用,以便更好地控制.
如果您使用的是redux,则可以使用redux thunk或redux-saga帮助程序库.如果您使用的是vuex,则可以在操作中处理此类副作用(请参阅此处https://vuex.vuejs.org/en/actions.html)


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!