如何从Angular Service中的API获取数据并将其存储以供将来的任何人使用 [英] How to get data from an API in a Angular Service and store it to be used by anyone in the future

查看:123
本文介绍了如何从Angular Service中的API获取数据并将其存储以供将来的任何人使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这更像是编写清洁代码/优化现有代码。
我正在编写我的Angular Services以从后端获取数据,如此

This is more of a writing clean code/ optimizing existing code. I am writing my Angular Services to fetch data from backend like this

angular.module('myApp').service('Auth', ['$http', '$q', 'Config', function($http, $q, Config) {
    this.getUser = function() {
        return $http.get(Config.apiurl + '/auth/user')
            .then(function(response) {
                return response.data;
            }, function(error) {
                return $q.reject(error.data);
            });
    };
}]);

现在,我在数据库中多次调用getUser函数。
现在的问题是,是否可以调用此服务来获取n次冗余数据,或者我应该将其保存在某个地方,例如rootcope将在以后访问?或者存储在根范围内将是糟糕的做法,我应该考虑一些其他选择或什么都没有?
想在这里获得Angular社区的一些观点。

Now in this, I am calling getUser function n number of times from the Database. Now the question is, is it okay to call this service to get n times redundant data or I should it be saved somewhere say rootscope to be accessed later? Or storing in root scope would be bad practice and I should consider some other option or nothing at all? Would like to get some views on Angular Community here.

推荐答案

以下是示例,了解如何使用工厂在整个应用程序中共享数据。

Here is a sample example on how to use factory for sharing data across the application.

让我们创建一个工厂可以在所有控制器的整个应用程序中使用,以存储数据并访问它们。

Lets create a factory which can be used in entire application across all controllers to store data and access them.

工厂的优点是可以在其中创建对象并在控制器中的任何位置初始化它们我们可以通过在工厂本身初始化它们来设置defult值。

Advantages with factory is you can create objects in it and intialise them any where in the controllers or we can set the defult values by intialising them in the factory itself.

工厂

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

    var SharedData = {}; // create factory object...
    SharedData.appName ='My App';
    return SharedData;
}]);

服务

app.service('Auth', ['$http', '$q', 'SharedData', function($http, $q,SharedData) {
   this.getUser = function() {

            return $http.get('user.json')
              .then(function(response) {
                  this.user = response.data;
                  SharedData.userData = this.user; // inject in the service and create a object in factory ob ject to store user data..
                  return response.data;
              }, function(error) {
                  return $q.reject(error.data);
              });

    };

}]);

控制器

var app = angular.module("app", []);
app.controller("testController", ["$scope",'SharedData','Auth',
  function($scope,SharedData,Auth) {

    $scope.user ={};
   // do a service call via service and check the shared data which is factory object ...
   var user = Auth.getUser().then(function(res){
       console.log(SharedData);
       $scope.user = SharedData.userData;// assigning to scope.
   });


  }]);

在HTML中

<body ng-app='app'>
    <div class="media-list" ng-controller="testController">

       <pre> {{user | json}}</pre>

    </div>

</body>

这篇关于如何从Angular Service中的API获取数据并将其存储以供将来的任何人使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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