How to persist web api data in AngularJS

2019-06-11 16:01发布

I have created a factory as a service to get some data from server using Web API call, but if i need to get same data again, I need to hit API again, I want to use same data in further places and don't want to make Web API call again.

Is there any way to persist data in angular js?

3条回答
萌系小妹纸
2楼-- · 2019-06-11 16:53

You can use HTML5 Web Storage for that.

localStorage.setItem("lastname", "Smith");
console.log(localStorage.getItem("lastname"));
查看更多
ゆ 、 Hurt°
3楼-- · 2019-06-11 16:55

if you're making an async call inside your service and the data you're fetching are "static" it makes sense to cache them to avoid a new overhead each time you need them. Cache is disabled by default.

$http({
 method: 'GET',
 cache: true
}
查看更多
我只想做你的唯一
4楼-- · 2019-06-11 17:02

Ways to sharing the data across the application :

1. Using service

We can create a service to set and get the data between the controllers and then inject that service in the controller function where we want to use it.

Service :

app.service('setGetData', function() {
  var data = '';
    getData: function() { return data; },
    setData: function(requestData) { data = requestData; }
});

Controllers :

app.controller('myCtrl1', ['setGetData',function(setGetData) {

  // To set the data from the one controller
  var data = 'Hello World !!';  
  setGetData.setData(data);

}]);

app.controller('myCtrl2', ['setGetData',function(setGetData) {

  // To get the data from the another controller  
  var res = setGetData.getData();
  console.log(res); // Hello World !!

}]);

Here, we can see that myCtrl1 is used for setting the data and myCtrl2 is used for getting the data. So, we can share the data from one controller to another controller like this without making any further API call.

2. Using Session storage

Create factory service that will save and return the saved session data based on the key.

app.factory('storageService', ['$rootScope', function($rootScope) {

    return {
        get: function(key) {
            return sessionStorage.getItem(key);
        },
        save: function(key, data) {
            sessionStorage.setItem(key, data);
        }
    };
}]);

controller :

Inject the storageService dependency in the controller to set and get the data from the session storage.

app.controller('myCtrl',['storageService',function(storageService) {

  // Save session data to storageService
  storageService.save('key', 'value');

  // Get saved session data from storageService
  var sessionData = storageService.get('key');

});
查看更多
登录 后发表回答