B
B
borisovdenis2018-05-13 13:42:17
Vue.js
borisovdenis, 2018-05-13 13:42:17

How to put Vue.http.interceptors in a separate file?

I need to set http interceptors. Now they are set in my main.js file. But to fence everything there, it’s not right and not convenient, I want to transfer the interceptors to a separate file. Those. do like this.

import {Loading} from 'element-ui';
import {LOADING_CONFIG} from './const';
import Vue from 'vue';

const addLoadingOnRequest = (request, next) => {
  const loading = Loading.service(LOADING_CONFIG);
  next(() => {
    loading.close();
  });
};

const showErrorMessageOnFailedRequest = (request, next) => {
  next(response => {
    if (response.status > 308) {
      alert('API Error');
    }
  })
};

Vue.http.interceptors.push(addLoadingOnRequest);
Vue.http.interceptors.push(showErrorMessageOnFailedRequest);

I did, but it doesn't work. The debugger does not enter these methods.
Can you tell me how to correctly separate the code into separate files in a Vue.js application?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
markmariner, 2018-06-07
@markmariner

Move only the interceptors to the interceptors.js file:

import {Loading} from 'element-ui';
import {LOADING_CONFIG} from './const';
import Vue from 'vue';

export const addLoadingOnRequest = (request, next) => {
  const loading = Loading.service(LOADING_CONFIG);
  next(() => {
    loading.close();
  });
};

export const showErrorMessageOnFailedRequest = (request, next) => {
  next(response => {
    if (response.status > 308) {
      alert('API Error');
    }
  })
};

With the export words, you export these constants for use in other files.
In the main.js file, import these constants and include them:
import {addLoadingOnRequest, showErrorMessageOnFailedRequest} from 'interceptors';

Vue.http.interceptors.push(addLoadingOnRequest);
Vue.http.interceptors.push(showErrorMessageOnFailedRequest);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question