2

I am writing a project which uses so many Axios calls from different pages. Instead of using Axios calls multiple times, is it possible to write a single Axios call function and use it in each pages.

For ex, define an "axiosCall" function once and than use it in different pages by just calling that function.

axiosCall (serviceName, parameter) {
  axios
    .get(`http://localhost/xApi/` + serviceName + `/` + parameter)
    .then(response => {
        return response.data
    })
    .catch(e => {
      this.exceptionHandler('Error at get ' + serviceName + ' : ', e)
    })
}

Then use it like

var userData = axiosCall('user',1)
var roleData = axiosCall('role',2)

Thanks in advance

dyte
  • 23
  • 1
  • 3
  • Definitely possible. What have you tried and what isn't working as expected? – thanksd Feb 08 '18 at 14:32
  • Indeed it is possible. Yet as far as I know, the best practice for this should be that you create service classes for each service, and include the axios calls (CRUD) for each service inside them. Then it would be like var userData = userService.getUserById(5); etc. – Red fx Feb 08 '18 at 14:35
  • I read about mixin, extending and inheritance in javascript. But actually I am new at JavaScript and so I could not analyse which is the best practice. So I am looking for a way to figure it out. – dyte Feb 08 '18 at 14:38
  • Look into Vuex for this. – ceejayoz Feb 08 '18 at 14:59

2 Answers2

2

There are a few ways to do this:

In your bootstrap file i.e main.js you could do Vue.prototype.$axiosCall = function () { ... } before you initialise Vue then within your components you could just call this.$axiosCall('user', 1).

Another way would be to use a mixin (axiosMixin.js):

export default {
  methods: {
    axiosCall () { ... }
  }
}

Then include it as a global mixin in your bootstrap file like: Vue.mixin(UserMixin) (again, in your bootstrap file before the initialise has been done).

tony19
  • 125,647
  • 18
  • 229
  • 307
webnoob
  • 15,747
  • 13
  • 83
  • 165
-3

Maybe not the best solution, but it can work

axios-conf.js

window.axios = require('axios');

window.axios.defaults.headers.common = {
    'CUSTOM_HEADER': 'SOME TEXT',
    'X-Requested-With': 'XMLHttpRequest'
};

window.axios.axiosCall = function(serviceName, parameter) {
  axios.get(`http://localhost/xApi/` + serviceName + `/` + parameter)
    .then(response => {
        return response.data
    })
    .catch(e => {
      this.exceptionHandler('Error at get ' + serviceName + ' : ', e)
    })
}
Nikola Gavric
  • 3,507
  • 1
  • 8
  • 16