1

I am new to Angular js and want to set the global variable that I can use it on different different services as webservice url.

I have implemented app.js (module) like this:

var app;
(function () {
    app = angular.module("ANG", []);

    app.value('user', {
        urlBase: ''
    });
})();

When I want to use this constants values I just define it in the service defination and use it but I want to store the details in that so no need to set values again and again.

Example:

When I login in the system I return some data with webserviceurl with it and I set that url in the value.urlBase in login controller.

But when I go to different service and want to use that it sets the values back to ''.

CODE to use constant values:

app.service('servicename', ["$http", "$q", 'user', function ($http, $q, user) {
//access the user here but it gives value ''.
console.log(user.urlBase);
}

How can I store at once and use it again and again?

3 rules
  • 1,359
  • 3
  • 26
  • 54

3 Answers3

1

You can actually use a 'constants' file, like so:

export default angular
  .module('my.module', [])
  .constant('someConstant', Object.freeze({
    foo: 1,
    bar: 2
  })
  .name;

We use Object.freeze() in ours, but you can use immutable.js or something like that to prevent mutation.

rrd
  • 5,789
  • 3
  • 28
  • 36
  • I want to set suppose foo value when I am logging in and want to use that after login in every services is it possible? Because values which I initialize in module when I use that in any service it initialize again and I want to get older value that was initialized at login time. – 3 rules Feb 28 '17 at 09:15
  • How I can use this in service and controller? – 3 rules Feb 28 '17 at 09:20
1

I suggest you have another service, rather than a value.

Pass a userService to your services, that contains the user object that is either accessible as a property, or retrieved via a getter:

app.factory('userService', function() {

    var user = {
        urlBase: ''
    };

    return {
        user: user
    };
};

app.service('servicename', ['userService', function (userService) {
    console.log(userService.user.urlBase);
}]);

Then where you set the urlBase, you are also passing the userService. Services are generally singletons, so it should preserve the user between other services.

UPDATE:

As you need to preserve the details between page refreshes, a cookie is not a bad solution. In your loginService, you set the cookie value, and in your other services, read from the cookie. This is done using the $cookies service in Angular (https://docs.angularjs.org/api/ngCookies/service/$cookies)

app.service('loginService', ['$cookie', function ($cookies) {
    $cookies.put('userUrl', 'http://urlhere');
}]);

app.service('servicename', ['$cookie', function ($cookies) {
    console.log($cookies.get('userUrl'));
}]);

Another option is to use local storage, and this SO has an example of doing so and preserving state:

How do I store data in local storage using Angularjs?

Community
  • 1
  • 1
Jono Stewart
  • 346
  • 1
  • 2
  • 11
  • 1
    You should set urlBase on successfull login **userService.user.urlBase="your url"** and you can use this in any where with add dependency userService. – Ankit Badiya Feb 28 '17 at 09:56
  • @AnkitBadiya No everytime when I try to use it it initialzed again and I got blank value in urlBase. – 3 rules Feb 28 '17 at 10:05
  • provide a plunkr link – Ankit Badiya Feb 28 '17 at 10:06
  • @AnkitBadiya please find this incomplete [jsFiddle](https://jsfiddle.net/MVDotNet/zvxkbr7w/2/) may be you can fix it sir. – 3 rules Feb 28 '17 at 10:28
  • @AnkitBadiya yes exactly what I wanted but in my case in my application page reload another url and new controller and new service call at that time it disappears I don't know what is the problem. Anyway thank you so much. I will figure out ahead. – 3 rules Feb 28 '17 at 11:35
  • @padhiyar if you application is SPA(single page application) then load service.js default and use lazy load to load controller.js then you will not get the issue. – Ankit Badiya Feb 28 '17 at 11:45
  • @padhiyar as Ankit Badiya has alluded to, a SPA is slightly different from a classic page-by-page application. A refresh will always wipe out the angular context. In fact, a page refresh will reload the entire Angular application. For a login service, consider setting a cookie value or consider local storage. (I will edit the answer above) – Jono Stewart Feb 28 '17 at 12:07
  • @AnkitBadiya No I have ASP.NET MVC with angular js application that navigate to different different url and I have one single single file controller.js and service.js file and app.js. app.js is file where I have set factory for urlBase. That is structure of my application. – 3 rules Feb 28 '17 at 12:07
  • @JonoStewart ok I understand what you say sir I am waiting for the updated answer. – 3 rules Feb 28 '17 at 12:11
  • @padhiyar updated now. There is another option also - some may argue is preferred over a cookie, as cookies can be tracked - which is to handle the user details on the server end and whenever a page is refreshed, fetch them from the server. You'd still need to store a reference to where to find the data on the server, again, local storage or a cookie, or even from a token in the url. – Jono Stewart Feb 28 '17 at 12:15
  • @JonoStewart As you defined update you have created two services one is to define and other is to use? Is it possible to set that cookie in module and use it in every service that will create in future? – 3 rules Feb 28 '17 at 12:17
  • 1
    @padhiyar correct - one is your login service, and the other is any other service that wants to read the value from the $cookies service. Cookies are passed between pages in the request headers, so page refreshes will preserve the values, until they time out. Check out the angular documentation (now linked in the answer) to see how to change timeouts. – Jono Stewart Feb 28 '17 at 12:22
  • @JonoStewart Ok I will look into that and try to implement hope will work for me. – 3 rules Feb 28 '17 at 12:37
0
You can use constant files like this.

app = angular.module("ANG", []);
app.constant('user', {
    urlBase: {
          'url':'what ever the URL is'
     }
});
Jaimin Raval
  • 146
  • 5