Angular $ http无法在$ routeProvider中解析

时间:2014-03-07 22:38:32

标签: javascript angularjs angular-http route-provider

我正在尝试将JSON文件中的数据显示到网页上。我的代码

angular.module('bioA.configs',['ngRoute'])
//Config routes
.config(['$routeProvider',function($routeProvider){
    $routeProvider.when('/',
    {
        templateUrl: 'list.tpl.html',
        controller: 'BioACtrl',
        resolve: {
            bioAList: ['$http',function($http){
                return $http.get('bioa.json');
            }]
        }
    });
}]);
//Controller to Manage the data
angular.module('bioA.controllers',['bioA.configs'])
.controller('BioACtrl',['bioAList','$scope',function($scope,bioAList){
    console.log(bioAList);
    $scope.samples = bioAList.data.samples;
}]);
angular.module('bioA',['ngRoute','bioA.controllers','bioA.configs','ui.bootstrap']);

$ http似乎无法解决。 这是控制台输出: Console output 我是AngularJS noob任何帮助表示赞赏:)我被卡住了。为什么解析的对象是ChildScope而不是承诺?

1 个答案:

答案 0 :(得分:1)

首先,你的包含在这里被颠倒了

controller('BioACtrl',['bioAList','$scope',function($scope,bioAList){

应该是

controller('BioACtrl',['$scope', 'bioAList',function($scope,bioAList){

其次,在尝试获取数据之前,您正尝试访问bioAList服务中的数据。这样做的正确方法是使用角度承诺。我修改了plnkr以实现此访问范例:

bioAList.getSamples().then(function(data) {
    $scope.samples = data.samples;
})

编辑:添加@OdeToCode指出的东西。

好点!你可以将$ http承诺作为服务返回。

return $http.get('bioa.json').success(function(data,status){
    return data;
})

并像你原来那样访问它。

希望这有帮助!