How to use AngularJs to load user location, which can be used in the entire application?

99 views Asked by At

In AngularJs, after I call get geoLocation and call a remote service to determine the location (city, state, country), how can I reuse this data in the entire application?

what I mean is, getting geoLocation and determining city are async, ideally, I only want to do those things once. After that, every time a new page is opened, I would like the controller just asking my geoService to get city or something.

But how can I do it?

I have tried to create a service, which exposes a property, say city. In the next controller, the property has no value, and I have to recall those methods. I thought a service should be singleton.

I could, use a cookie after the first time it is loaded.

But I really want to know, how other people would handle this kind of thing?

Thanks!

1

There are 1 answers

2
Dmitri Algazin On BEST ANSWER

you should look for sharing service data across multiple controllers, something like that:

app.service('cache', function ($http, $q) {
          var mycache={};
          return {
              getdata: function (key) {
                  var deferred = $q.defer();
                  if (mycache[key]) {
                      deferred.resolve(mycache[key]);
                  }
                  else {
                      $http.get('api/your_location').then(function (data) {
                          mycache[key] = data.data;
                          deferred.resolve(mycache[key]);
                      });
                  }
                  return deferred.promise;
              }
          }
      });


      app.controller('test', function ($scope, cache) {
          cache.getdata('cache').then(function (data) {
              $scope.data = data;
          });
     });

       app.controller('test1', function ($scope, cache) {
          //since data is already cached now it will server the cached data
          cache.getdata('cache').then(function (data) {
              $scope.data = data;
          });
     });