2

first of all thanks in advance for the feedback. As I am new to es6 and vuejs I'm starting to have problems using imported Services module throughout the application. The end goal would be to move everything that uses Axios to one BaseService too.

[Vue warn]: Error in mounted hook: "TypeError: __WEBPACK_IMPORTED_MODULE_0__services_AuthService__.a.getCurrentUser is not a function"

AuthService.js

import BaseService from './BaseService'

export default class AuthService {

  setCurretUser( user )
  {
    localStorage.setItem("currentUser", user);
  }

  getCurrentUser()
  {
    return localStorage.getItem("currenUser");
  }

}

App.vue

import Axios from 'axios'
import Navbar from './partials/Navbar'
import Sidebar from './partials/Sidebar'
import AuthService from '../services/AuthService'

export default {
  name: 'app',
  components: {
    Navbar,
    Sidebar
  },
  mounted() {
    console.log('Component mounted.')
  },
  created() {
    Axios.get('api/user')
      .then(function (response) {
        AuthService.setCurrentUser(response.data);
        console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    });
  }
}

1 Answer 1

4

If you are going to use AuthService class as a container for methods, convert them to static so they can be called without instantiating the class (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Static_methods)

export default class AuthService {

  static setCurretUser( user )
  {
    localStorage.setItem("currentUser", user);
  }

  static getCurrentUser()
  {
    return localStorage.getItem("currenUser");
  }

}

Or you could also contain them in an object:

export default {

  setCurretUser( user )
  {
    localStorage.setItem("currentUser", user);
  },

  getCurrentUser()
  {
    return localStorage.getItem("currenUser");
  }

}
Sign up to request clarification or add additional context in comments.

2 Comments

Or export them as named exports, e.g. export function setCurrentUser(user){ ... } and do import * as AuthService from
Wow, of course, I'm calling them statically. What would be the clean way to instantiate a class to be used in the .vue object.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.