2013-08-21 109 views
0

guys 我是Angularjs的新手,这里是我的新单页面应用程序的一些代码。但我认为我做得不对。 这里是我的戈德: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.all()获取值。但它在HomeController上的工作非常完美。

我对服务和工厂都很满意。我想我只是以错误的方式去做? 感谢您的帮助!

回答

1

你的错误是,你试图以同步的方式从服务器中检索数据,这在角度上不起作用(在一般情况下也是如此)。

更改服务代码:

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

吉文嗨,现在我就'不能从控制台读取undefined'的特性“长度”,可能是什么问题您认为? –

+0

你有没有检查你在response.data中得到了什么。这可能不是你想要的数组。把一个断点放在$ scope.towns = response.data;并检查包含哪些响应。 –

+0

Iv将所有数据从异步更改为静态JSON字符串,节省了大量时间。稍后我会在完成此项目时回到异步服务的东西。再次感谢您的帮助! –

1

Town.all()返回一个承诺。承诺就像将来会有一段时间回归的价值。这不是直接的价值。这是一个可用于检索值的对象。

所以不是

$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;  
    }); 
+0

不需要将Town.all()分配给'$ scope.towns' – zsong

+0

嗨,Christoph,但'response.data'返回'undefined'。 :( –

+0

@sza谢谢,这是一个马虎的复制和粘贴错误 – Christoph