AngularJS ui-router解析未定义

时间:2015-07-11 13:42:03

标签: angularjs angular-ui-router undefined

我已经从使用ngRoute转移到ui-router。我正在尝试解决路径中的Factory调用以在控制器中使用,但在输出到控制台时未定义。这是工厂:

'use strict';

angular.module('angular10App')

.factory('AirportService', function ($http) {

return {

    getAirports: function () {

        var airports = $http.get('../json/airports.json')
            .then(function (response) {

                console.log(response.data); //Outputs an array of objects

                return response.data;
            });
    }
});

这是路线:

'use strict';

angular.module('angular10App')
    .config(function ($stateProvider) {
    $stateProvider
        .state('selectFlights', {
            url: '/select_flights',
            templateUrl: 'app/selectFlights/selectFlights.html',
            controller: 'SelectFlightsCtrl',
            resolve: {

                AirportService: 'AirportService',

                airports: function (AirportService) {
                    return AirportService.getAirports();
                }
            },
        });
    });

这是控制器:

'use strict';
angular.module('angular10App')
.controller('SelectFlightsCtrl', function ($scope, airports) {

$scope.selectedAirport = null;

    $scope.airports = airports;
    console.log($scope.airports); //undefined
});

1 个答案:

答案 0 :(得分:3)

尝试将您的解决方案块更改为:

resolve: {
    airports: function (AirportService) {
        return AirportService.getAirports();
    }
}

getAirPorts函数修改为:

function getAirports () {
  // You need to return the $http promise (or in your case, 'var airports');
  return $http.get('../json/airports.json')
    .then(function (response) {
      console.log(response.data); //Outputs an array of objects
      return response.data;
    });        
}