Search code examples
angularjsangularjs-service

Share Data between Services in angular js 1.4


Sample URLs:
/users/api/getUser
/users/api/addUser
/users/api/deleteUser/{userId}

I want to store the common path(/users/api) in a global variable and pass it to each service so as to concate it with Request URL before calling REST endpoint. I have created one class and stored url prefix. But I am not able to get its value in Service. Below is the code snippet.

import CommonVariables from './commonVariables';

class UserService {

/*@ngInject*/
    constructor($rootScope, Rest){
        Object.assign(this, {$rootScope, Rest});
    }

    getUsers() {
        console.log("commonVariables.getBaseURL: ", CommonVariables.baseURL);
        console.log("commonVariables.getBaseURL: ", CommonVariables.getBaseURL());
        return this.Rest.one("/users/api/getUser").get();
    }

     addUserDetails(request) {
        return this.Rest.one("/users/api/addUser").customPOST(request);
     }
}

export default UserService

CommonVariable

class CommonVariables {
/*@ngInject*/
    constructor($rootScope){
        Object.assign(this, {$rootScope});
         let vm = this;
         vm.baseURL = "/users/api";
    }

    getBaseURL() {
        console.log("getBaseURL called");
        return "/users/api";
    }

}

export default CommonVariables

Solution

  • Change export default CommonVariables to export default new CommonVariables();