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

Nic*_*nev 5 javascript vue.js axios

我想将axios请求逻辑移至Vue.js应用程序中的单独服务。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();
Run Code Online (Sandbox Code Playgroud)

Pub*_*oda 6

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

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

由于我们没有调用.thenaxios 结果,因此 promise 将不会被解析。相反,promise 本身将从这个方法返回。因此它可以如下使用,

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

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