简体   繁体   English

Angular JS:使用$ http.get()导入JSON数据 - 在控制器中工作,不在服务中 - 为什么?

[英]Angular JS: importing JSON data with $http.get() - works in controller, does not in a service - WHY?

I'm trying to import JSON data into an angularJS application. 我正在尝试将JSON数据导入angularJS应用程序。 I split my app into a controller and the import-service, but both in different files. 我将我的应用程序拆分为控制器和导入服务,但两者都在不同的文件中。 I'm also using bower, grunt and yeoman (that's due to work, I'm not quite used to these, maybe there's also a problem.) 我也在使用bower,grunt和yeoman(这是因为工作,我不太习惯这些,也许还有一个问题。)

The strange behavior is: 奇怪的行为是:

I wanted to retrieve the JSON data with a $http.get() and resolve it - all within a service, so that I can hand out the data object from there to the main controller and won't have to resolve it there. 我想用$ http.get()检索JSON数据并解决它 - 所有这些都在服务中,这样我就可以将数据对象从那里分发给主控制器,而不必在那里解析它。 Strangely, I didn't get any data, it was empty or not readable. 奇怪的是,我没有得到任何数据,它是空的或不可读的。 Then I handed out the promise which I the $http.get() mehtod gives back and resolved it in the controller. 然后我发出了$ http.get()mehtod给出的承诺,并在控制器中解析了它。 That's not what I wanted, but now it works.... but why? 这不是我想要的,但现在它有效......但为什么呢?

I guess it's a schmall misstake somehwere but neither me nor my team members can find one. 我想这是一个骗子,但我和我的团队成员都找不到。 Strangely, doing a little test-app without grunt, yeoman and bower it worked. 奇怪的是,做一个没有咕噜声的小测试应用程序,自耕农和凉亭它起作用了。

I'd appreciate every hint or idea... Jana 我很欣赏每一个提示或想法...... Jana

Here's my code from the NOT working version , first the main module with controller: 这是我的代码来自NOT工作版本 ,首先是带有控制器的主模块:

/** Main module of the application. */
(function () {
  'use strict;'
  angular.module('angularRegelwerkApp', [])
    .controller('RegelwerkCtrl', function ($scope, CategoryFactory) {

      $scope.categories = CategoryFactory.getCategories();
      $scope.subcategories = CategoryFactory.getSubCategories();

    }
  );
})();

Service-part: 服务部分:

(function () {
  'use strict';
  var app = angular.module('angularRegelwerkApp')
    .service('CategoryFactory',
    function ($http) {

      var categories = [];
      var subcategories = [];

      $http.get("../mockdata/categories.json").then(function (response) {
        categories = response.data;
      })
      $http.get('../mockdata/subcategories.json').then(function (response) {
        subcategories = response.data;
      })
      return {
        getCategories: function(){
          return categories;
        },
        getSubCategories: function(){
          return subcategories;
        }
      }
    }
  );
})();

Here's my code from the WORKING version , first the main module with controller: 这是我的WORKING版本的代码,首先是带控制器的主模块:

/** Main module of the application. */
(function() {
  'use strict;'
  angular.module('angularRegelwerkApp', [])
    .controller('RegelwerkCtrl', function ($scope, CategoryFactory) {

      $scope.categories = [];
      $scope.subcategories = [];

      CategoryFactory.getCategories().then(function(response) {
        $scope.categories = response.data;
      });
      CategoryFactory.getSubCategories().then(function(response) {
        $scope.subcategories = response.data;
      });
    }
  );
}
)();

Service-part: 服务部分:

(function () {
  'use strict';
  var app = angular.module('angularRegelwerkApp')
    .service('CategoryFactory',
    function ($http, $q) {

      var categoryURL = "../mockdata/categories.json";
      var subcategoryURL = '../mockdata/subcategories.json';

      function getSubCategories() {
        return $http.get(subcategoryURL);
      }
      function getCategories() {
        return $http.get(categoryURL);
      }
      return {
        getCategories: getCategories,
        getSubCategories: getSubCategories
      }
    }
  );
})();

This is destroying your reference, so loop over the data from the server and push it into the variables you need: 这会破坏您的引用,因此从服务器循环数据并将其推送到您需要的变量中:

  $http.get("../mockdata/categories.json").then(function (response) {
    for(var x = 0; x < response.data.length; x++){
        categories.push(response.data[x]);
    }
  });

$http call is by default asynchronous. $ http调用默认是异步的。

So in your first version, when you write like $scope.categories = CategoryFactory.getCategories(); 因此,在您的第一个版本中,当您编写类似$scope.categories = CategoryFactory.getCategories(); you get empty categories, since by the time you access categories, it may not have been loaded with response data. 你得到空类别,因为当你访问类别时,它可能没有加载响应数据。

your app flows like this - 你的应用流程如下 -

  1. you load the controller 你加载控制器
  2. you call the service 你打电话给服务
  3. service calls $http 服务电话$ http
  4. you try to access categories (but data will not be available until response is returned from server) 您尝试访问类别(但在从服务器返回响应之前,数据将不可用)
  5. $http.then loads data to $scope.categories $ http.then将数据加载到$ scope.categories

You are storing your data in Angular primitives and these don't update. 您将数据存储在Angular基元中,并且这些基元不会更新。 instead store all your data in an object and it shoudl work (you'll also need to update controller) 而是将所有数据存储在一个对象中,它可以工作(你还需要更新控制器)

(function () {
  'use strict';
  var app = angular.module('angularRegelwerkApp')
    .service('CategoryFactory',
    function ($http) {

      var data = {};

      $http.get("../mockdata/categories.json").then(function (response) {
        data.categories = response.data;
      })
      $http.get('../mockdata/subcategories.json').then(function (response) {
        data.subcategories = response.data;
      })
      return {
        getCategories: function(){
          return data.categories;
        },
        getSubCategories: function(){
          return data.subcategories;
        }
      }
    }
  );
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM