如何在AngularJS中保留Web API数据 [英] How to persist web api data in AngularJS

查看:99
本文介绍了如何在AngularJS中保留Web API数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个工厂作为服务,以使用Web API调用从服务器获取一些数据,但是如果我需要再次获取相同的数据,则需要再次点击API,我想在其他地方使用相同的数据并且不要不想再次调用Web API.

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.

有什么方法可以将数据保存在angular js中吗?

Is there any way to persist data in angular js?

推荐答案

如何在应用程序之间共享数据:

1..使用服务

我们可以创建一个服务,以setget之间的数据在controllers之间,然后将该服务注入到控制器功能中要使用的位置.

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.

服务:

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

控制器:

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 !!

}]);

在这里,我们可以看到myCtrl1用于设置数据,而myCtrl2用于获取数据.因此,我们可以像这样从一个controlleranother controller共享数据,而无需进行任何进一步的API调用.

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..使用会话存储空间

创建工厂服务,该服务将根据密钥保存并返回保存的会话数据.

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);
        }
    };
}]);

控制器:

将控制器中的storageService依赖性注入到setget会话存储中的数据.

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');

});

这篇关于如何在AngularJS中保留Web API数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆