Peter
Peter

Reputation: 312

Why is $http request not working in this Cordova Application?

I am trying to bring the data in the code to my application, here is the factory.

angular.module('starter.services', [])

    .factory('Locations', function ($http, $q) {
        // Might use a resource here that returns a JSON array
            var url = "https://portal.mobilequbes.com/api/kiosks?callback=JSON_CALLBACK";
            var locations = function () {
                $http.jsonp(url)
                    .then(function (result) {
                        return result.data;
                    });
            };

        return {
            all: function () {
                return locations;
            },
            get: function (locId) {
                for (i = 0; i < locations.length;i++){
                    if (locations[i].friendlyName == parseInt(locId)) {
                        return locations[i];
                    }
                }
            }
        }
    });

and my controller:

.controller('MapCtrl', function ($scope, $http, Locations) {
    $scope.locations = Locations.all();
    $scope.createMarks = function () {
        createList(Locations.all());
    }
})

When it loads, it just loads nothing or two objects that look like this: ' '

I am not sure why because I cannot seem to discern any problems and I feel like I have read this to death. I have tested the return function using jsFiddle and it worked fine so it has something to do with ionic/cordova I am fairly sure.

Upvotes: 0

Views: 93

Answers (1)

Debasish Mohapatra
Debasish Mohapatra

Reputation: 856

In your factory do,

angular.module('starter.services', [])

.factory('Locations', function ($http, $q) {
    // Might use a resource here that returns a JSON array
        var url = "https://portal.mobilequbes.com/api/kiosks?callback=JSON_CALLBACK";
        var locations = [];  //storing locations for future usage

    return {
        all: function () {
            return $http.jsonp(url)
                .then(function (result) {
                    locations = result.data;
                    return result.data;
                });
        },
        get: function (locId) {
            for (i = 0; i < locations.length;i++){
                if (locations[i].friendlyName == parseInt(locId)) {
                    return locations[i];
                }
            }
        }
    }
});

And in your Controller,

.controller('MapCtrl', function ($scope, $http, Locations) {
    Locations.all().then(function (locations) {
         $scope.locations = locations;
    });
    $scope.createMarks = function () {
        createList(Locations.all());
    }
})

Now the Locations.all() method is returning a promise which will resolve to result.data in your controller and you can access locations.

Previously you are not returning anything so $scope.locations was undefined.

Upvotes: 1

Related Questions