0

i'm trying to use this kind of structure.

I have my axios calls in a service file and then call them in vue files.

So i have this js file

const DashboardService = {

    getStationList() {

        let url = '/api/stations/list'
        ApiService.get(url) //ApiService is an Axios wrapper
            .then(response => {
                console.log(response.data) //data are logged, function is called
                response.data
            })
    }
}

export default DashboardService

Then in the Vue File i have this:

import DashboardService from '@/_services/admindashboard.service'
export default {
 methods: {
      getMarkers() {
        let result = DashboardService.getStationList()
        console.log(result) //undefined

      }},
    mounted() {
      this.getMarkers()
    }

}

I can't understand why result is undefined because che getStationList() function gets called... when the component is mounted the functions should have returned the response... how can i solve this situation?

MarioC
  • 2,934
  • 15
  • 59
  • 111

2 Answers2

1

getStationList is an async function, so you'll need to await it's result (or use then). For example:

async mounted() {
  this.markers = await DashboardService.getStationList();
},

Also see this question for more details.

Next, you are missing a return in the implementation of getStationList.

const DashboardService = {
  getStationList() {
    const url = '/api/stations/list';
    ApiService.get(url).then(response => {
      return response.data;
    });
  },
};

or perhaps:

const DashboardService = {
  async getStationList() {
    const url = '/api/stations/list';

    try {
      const response = await ApiService.get(url);
      return response.data;
    } catch (error) {
      console.error(error);
      return [];
    }
  },
};
David Weldon
  • 63,632
  • 11
  • 148
  • 146
0

The result is undefined because getStationList is not returning anything.

You can consider turning your api call into an async function that returns the result.

const DashboardService = {
    async getStationList() {
        let url = '/api/stations/list';
        return ApiService.get(url);
    }
}

export default DashboardService

And in your component

methods: {
    async getMarkers() {
        let result = await DashboardService.getStationList();
        console.log(result);

   }
},

If you don't want to use the async await syntax. You can return a the promise from your service and utilize the result on your component, as so:

methods: {
    getMarkers() {
        DashboardService.getStationList().then(result => {
            console.log(result);
        });
   }
},
Daniel Ormeño
  • 2,743
  • 2
  • 25
  • 30