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

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

问题描述

这更像是编写干净的代码/优化现有代码.我正在编写我的 Angular 服务来像这样从后端获取数据

angular.module('myApp').service('Auth', ['$http', '$q', 'Config', function($http, $q, Config) {this.getUser = function() {返回 $http.get(Config.apiurl + '/auth/user').then(功能(响应){返回 response.data;}, 函数(错误){返回 $q.reject(error.data);});};}]);

现在,我从数据库中调用 getUser 函数 n 次.现在的问题是,是否可以调用此服务来获取 n 次冗余数据,或者我应该将其保存在某个地方,例如 rootscope 以便稍后访问? 或者存储在 root 范围中将是不好的做法,我应该考虑其他选择还是什么都不考虑?想在此处获得对 Angular 社区的一些看法.

解决方案

这是一个示例 example 如何使用工厂在整个应用程序中共享数据.

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

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

工厂

app.factory('SharedData',['$http','$rootScope',function($http,$rootScope){var SharedData = {};//创建工厂对象...SharedData.appName ='我的应用';返回共享数据;}]);

服务

app.service('Auth', ['$http', '$q', 'SharedData', function($http, $q,SharedData) {this.getUser = function() {返回 $http.get('user.json').then(功能(响应){this.user = response.data;SharedData.userData = this.user;//注入服务并在工厂对象中创建一个对象来存储用户数据..返回 response.data;}, 函数(错误){返回 $q.reject(error.data);});};}]);

控制器

var app = angular.module("app", []);app.controller("testController", ["$scope",'SharedData','Auth',函数($scope,SharedData,Auth){$scope.user ={};//通过服务进行服务调用并检查工厂对象的共享数据...var user = Auth.getUser().then(function(res){控制台日志(共享数据);$scope.user = SharedData.userData;//分配给作用域.});}]);

在 HTML 中

<div class="media-list" ng-controller="testController"><预>{{用户 |json}}</pre>

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

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.

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.

Factory

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

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

Service

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

    };

}]);

Controller

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


  }]);

In HTML

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

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

    </div>

</body>

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

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