Reputation: 3296
I am using Vue CLI to load an instance property for Axios. I have added a couple of interceptors and I will like the ability to turn them off when using the Axios instance from inside a Vue component.
In the documentation Axios suggests you just label the interceptor then eject
is later via the name.
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
So the issue I am having, is that I can't figure out who I can name my interceptor for use in components.
Here is my setup:
api-client.js
import axios from 'axios'
var client = axios.create({
baseURL: process.env.API_DOMAIN,
headers: { Accept: 'application/json' }
})
var unauthorizedInterceptor = client.interceptors.response.use(function (response) {
return response
}, function (error) {
...
return Promise.reject(error)
})
export default client
main.js
import Vue from 'vue'
import apiClient from './api-client'
Vue.prototype.$apiClient = apiClient
new Vue({
el: '#app',
...
})
component.js
<template>
...
</template>
<script>
export default {
data () {
return {
username: null,
email: null,
firstName: null,
lastName: null
}
},
methods: {
updateAccount () {
var self = this
var data = {
username: this.username,
email: this.email,
first_name: this.firstName,
last_name: this.lastName
}
self.$apiClient`enter code here`.interceptors.request.eject(unauthorizedInterceptor) // Remove interceptor here.
self.$apiClient.patch('/me')
.then(function () {
...
})
.catch(function () {
...
})
}
}
}
</script>
How could I name the interceptor to eject it at the component level?
Upvotes: 3
Views: 3139
Reputation: 82449
Export the interceptor from your api-client.js
and import it where you want to eject it.
api-client.js
export let unauthorizedInterceptor = ...
export default client
component.js
import { unauthorizedInterceptor } from "./api-client"
...
self.$http.interceptors.request.eject(unauthorizedInterceptor)
You may want to export the interceptor function itself as well so that you could add it back if needed.
Alternatively export a function or two that can do this management for you.
api-client.js
let unauthorizedInterceptor
export function removeUnauthorizedInterceptor() {
axios.interceptors.request.eject(unauthorizedInterceptor)
}
export function addUnauthorizedInterceptor(){
unauthorizedInterceptor = axios.interceptors.response.use(...)
}
component.js
import { removeUnauthorizedInterceptor} from "./api-client"
removeUnauthorizedInterceptor()
Upvotes: 4