0

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

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.