简体   繁体   中英

Angular $http not resolving in $routeProvider

I am trying to display data from a JSON file onto the webpage. My Code

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']);

The $http doesnt seem to resolve. here is the console output: 控制台输出 I am AngularJS noob any help is appreciated :) I am stuck. Why is the resolved object a ChildScope rather than being a promise ?

first of all, your includes are reversed here

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

Should be

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

Second, you are trying to access data in your bioAList service before you even fetch it. The correct way to do this is with angular promises. I modified the plnkr to acheive this access paradigm:

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

EDIT: add the thing that @OdeToCode points out.

Good point! you can just return the $http promise as the service.

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

And access it like you originally had.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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