Craig Roberts
Craig Roberts

Reputation: 171

Service process http.get results into new array and return to calling controller

I am wanting to keep biz logic in service and return array object of values wanted to my controller.

   service.getBooking($scope.bookingId).success(function (data) {
            $scope.booking = data;
            console.log("3 storeno: " + $scope.booking.Storeno);

In my service I have:

testLabApp.factory('service', ['$http', function ($http) {

var getBooking = function (bookingId) {
    console.log("[getBooking] bookingId = " + bookingId);

    var config = {headers: { 'Accept': 'application/json;odata=verbose' }};

    return $http.get(theUrl, config).success(function (data) {

            var booking = [];

            console.log("1 data.d.results = " + data.d.results.length);

            var e = data.d.results[0];
            booking = {
                Id: e['Id'],
                Storeno: e['Title']
            };

            console.log("2 Done = Id: " + booking.Id + " | Store no: " + booking.Storeno);

            return booking;
        }, function (er) {
            alert(er);
        });
}

return {
    getBooking: getBooking
}

The problem is that I expect a booking[] to be returned from getBooking service call, but console.log shows "3 storeno:" as undefined.

"1 data.d.results" is 1 as I expect and "2 Done..." shows the Id and Storeno values I would expect.

Any suggestions please on what is amiss.

Regards Craig

Upvotes: 0

Views: 1054

Answers (1)

Erazihel
Erazihel

Reputation: 7605

There is an error since your service returns the call of the $http.get and not the result as expected. Try using a callback method like this:

Controller:

service.getBooking($scope.bookingId, function(err, data) {
    if (err) throw err;

    $scope.booking = data;
    console.log("3 storeno: " + $scope.booking.Storeno);
}

Service:

testLabApp.factory('service', ['$http', function ($http) {

var getBooking = function (bookingId, callback) {
    console.log("[getBooking] bookingId = " + bookingId);

    var config = {headers: { 'Accept': 'application/json;odata=verbose' }};

    $http.get(theUrl, config).success(function (data) {    
        console.log("1 data.d.results = " + data.d.results.length);

        var e = data.d.results[0];
        var booking = {
            Id: e['Id'],
            Storeno: e['Title']
        };

        console.log("2 Done = Id: " + booking.Id + " | Store no: " + booking.Storeno);

         callback(null, booking);
     }.error(err) {
         callback(err);
     });
}

return {
    getBooking: getBooking
}

Upvotes: 1

Related Questions