Angularjs:无法迭代或从服务结果中获取结果

Angularjs: Unable to iterate or get results from service result

本文关键字:结果 服务 获取 迭代 Angularjs      更新时间:2023-09-26

伙计们我是Angularjs的新手,下面是我新的单页应用程序的一些代码。但我觉得我做得不对。这是我的教友:

var TownApp=angular.module('TownApp',['ngRoute','ngResource']);
TownApp.service('Town', function($http) {
    this.all = function() {
        return $http.get('/database.json').then(function(response){
          return response.data;
        })
    };
});
var HomeCtrl = TownApp.controller('HomeCtrl',function($scope,Town){
  $scope.towns = Town.all();
});
var TownCtrl = TownApp.controller('TownCtrl',function($scope, $routeParams, Town){
  console.log(Town.all().length)
  $scope.towns = Town.all();
  console.log($scope.towns.length)
  //........
})
TownApp.config(['$routeProvider', function($routes) {
  $routes.when('/',{
    templateUrl : 'welcome.html',
    controller : 'HomeCtrl'
  }).when('/town/:townId',{
    templateUrl : 'town.html',
    controller : 'TownCtrl'
  }).otherwise({
    redirectTo : '/'
  });
}]);

所以,问题是你可以在Town controller中看到这两个控制台日志,它们都返回了"未定义"。因此,我无法迭代或从Town.all()中获取值。但它在HomeController上运行得很完美。

我在服务和工厂方面都做过三次。我觉得我只是做错了?谢谢你的帮助!

您的错误是试图以同步的方式从服务器检索数据,这在angular中不起作用(通常在javascript中也不起作用)。

将服务代码更改为:

TownApp.service('Town', function($http) {
    this.all = function() {
        return $http.get('/database.json');
    };
});

然后将控制器代码更改为:

 TownApp.controller('HomeCtrl',function($scope,Town){
    Town.all().then(function(response)) {
      $scope.towns = response.data;
      console.log($scope.towns.length);
    }
}

Town.all()返回一个promise。承诺就像一种价值,在未来的某个时候会被回报。这不是直接的价值。它是一个可以用来检索值的对象。

所以不是

$scope.towns = Town.all();

您需要:

Town.all()
    .then(function(response){
        //if the promise we are dealing with is the promise that was directly 
        //returned from the $http call, then we need response.data
        //if it was projected to hold `response.data` before (as in the initial question)
        //then "response" here is already holding our data.
        $scope.towns = response;    
    });