Angular chain defers in config resolve not working

186 views Asked by At

I've been bashing my head at this most of the day and cannot get $scope.weatherData to resolve into anything other than undefined :(

This is my view1 controller:

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

Here is the 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;
}]);

The location is acquired, an api get request is made to the weather server but $scope.weatherData never gets populated.

0

There are 0 answers