服务进程 http.get 结果放入新数组并返回调用控制器 [英] Service process http.get results into new array and return to calling controller

查看:22
本文介绍了服务进程 http.get 结果放入新数组并返回调用控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想保持业务逻辑在服务中并将想要的值的数组对象返回给我的控制器.

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);

在我的服务中,我有:

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
}

问题是我希望从 getBooking 服务调用返回一个 booking[],但是 console.log 显示3 storeno:"为未定义.

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"是我期望的 1,2 Done..."显示了我期望的 Id 和 Storeno 值.

"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.

问候克雷格

推荐答案

出现错误,因为您的 service 返回的是 $http.get 的调用而不是结果如预期.尝试使用这样的 callback 方法:

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:

控制器:

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

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

服务:

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
}

这篇关于服务进程 http.get 结果放入新数组并返回调用控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆