配置中的角度链延迟解决不起作用

时间:2015-06-23 05:16:03

标签: javascript angularjs promise deferred

我一直在这一天大部分时间都在猛烈抨击,并且无法将$ scope.weatherData解析为未定义的任何内容:(

这是我的view1控制器:

'use strict';

angular.module('myApp.view1', ['ngRoute'])

    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/view1', {
            templateUrl: 'view1/view1.html',
            controller: 'View1Ctrl',
            resolve: {
                weatherData: ['$q', 'weatherSvc', function ($q, weatherSvc, options) {
                    var lat = 0;
                    var lon = 0;
                    var deferred = $q.defer();

                    navigator.geolocation.getCurrentPosition(
                        deferred.resolve,
                        deferred.reject,
                        options);

                    deferred.promise.then(function (position) {
                        lat = position.coords.latitude;
                        lon = position.coords.longitude;
                        console.log('lat:' + lat + ' lon:' + lon);
                        var data = weatherSvc.query(lat, lon);
                        console.log(data); // <-- data is a promise at this point but log has already fired in the controller
                        data.then(function(data){
                            console.log(data.data);
                            return data;
                        });
                    });
                }]
            }
        });
    }])

    .controller('View1Ctrl', ['$scope', 'weatherData', function ($scope, weatherData) {
        $scope.weatherData = weatherData;
        console.log(weatherData);
    }]);

这是weatherSvc

angular.module('myApp.services', [])
.factory('weatherSvc', ['$http', function ($http) {
    'use strict';
    function rangeLimit(value, min, max) {
        value = (value >= min) ? value : min;
        value = (value <= max) ? value : max;
        return value;
    }

    var sdo = {
        query: function (lat, lon, refresh) {
            // validations
            refresh = refresh || false;
            // valid lat = -90...90
            // valid lon = -180...180
            lat = rangeLimit(lat, -90, 90);
            lon = rangeLimit(lon, -180, 180);

            var promise = $http({
                method: 'GET',
                url: 'http://api.openweathermap.org/data/2.5/forecast/daily?lat=' + lat + '&lon=' + lon + '&mode=json'
            });
            promise.success(function (data, status, headers, conf) {
                return data;
            });
            return promise;
        }
    };
    return sdo;
}]);

获取位置,向天气服务器发出api get请求,但$ scope.weatherData永远不会被填充。

0 个答案:

没有答案