【问题标题】:Angular $http not resolving in $routeProviderAngular $http 未在 $routeProvider 中解析
【发布时间】:2014-03-07 22:38:31
【问题描述】:

我正在尝试将 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 似乎没有解决。 这是控制台输出: 我是 AngularJS noob 任何帮助表示赞赏:) 我被卡住了。为什么解析的对象是 ChildScope 而不是 Promise?

【问题讨论】:

  • 请提供适用的 HTML。
  • 从你的错误中你得到未定义的samples,但不是data。听起来bioAList 已经创建,但现在有data
  • @onaclov2000 这是plunk
  • 这似乎是一个异步请求,因此您需要监听成功或失败,而不仅仅是返回 $http.get('bioa.json');
  • @emailnitram 我已经更新了plunk,在控制台上返回的状态是 200,这意味着数据应该在控制器中可用(?)。

标签: javascript angularjs angular-http route-provider


【解决方案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;
})

并像原来一样访问它。

希望这会有所帮助!

【讨论】:

  • 如果避免使用 $q,您可以编写更少的代码。从那时起或成功的返回值将被包装在一个承诺中。您也不需要在控制器中解析承诺,因为这就是解析函数的设计目的。见:plnkr.co/edit/zaOYzlCFKqVYF9ycs9aG?p=preview
  • 非常感谢!!只需修复依赖顺序即可修复它。 @odetocode 是的,我认为我们不需要使用 $q 因为 $http 在解析后返回一个承诺。
猜你喜欢
  • 2015-10-29
  • 1970-01-01
  • 1970-01-01
  • 2014-04-26
  • 1970-01-01
  • 2014-07-07
  • 1970-01-01
  • 2019-11-07
  • 1970-01-01
相关资源
最近更新 更多