AngularJS控制器/工厂返回未定义的对象

3

在调用restful web api2时,Angular控制器返回undefined结果。我看到了许多有关此问题的帖子,但似乎没有解决我的问题。我有一个控制器,用它调用restful web api2。使用fiddler我可以看到调用已经成功并返回200响应,但我似乎永远无法得到结果,我知道这是异步调用。以下是工厂和控制器的代码。我还试图将回调显式地发送到工厂中,但此方法甚至导致未定义对象结果,根本不能正常工作。我真的陷入了困境,而且我刚刚开始接触Angularjs,请问是什么问题?目前,我已将控制器调用连接到按钮进行显式测试。

**FACTORY NO EXPLICIT CALL-BACK** 
casenoteApp.factory('MyFactory', function ($http) {


var factory = {};

var urlBase = 'http://xxxxxx/api/Client';


factory.getClients = function (userLogin) {

    return $http.get(urlBase + '/' + userLogin);
};


return factory;
});

**CONTROLLER NO EXPLICIT CALL-BACK** 
casenoteApp.controller('MyController', MyController);

function MyController($scope, MyFactory) {


$scope.addCustomer = function () {

    MyFactory.getClients(123456)
       .success(function (clients) {

            var curCust = clients;
            $scope.status = clients.last_name;

        })
       .error(function (error) {
           $scope.status = 'Unable to load client data: ' + error.message;
       });        

}


}

**FACTORY PASSING IN CALL-BACK**
casenoteApp.factory('MyFactory', function ($http) {


var factory = {};

var urlBase = 'http://xxxxxx/api/Client';

factory.getClients = function (userLogin, callback) {

    return $http.get(urlBase + '/' + userLogin).success(callback)

}

return factory;
});


**CONTROLLER PASSING IN CALL-BACK**
casenoteApp.controller('MyController', MyController);

function MyController($scope, MyFactory) {


$scope.addCustomer = function () 



    MyFactory.getClients(123456, function(clients) {

            var curCust = clients[0];
            $scope.status = clients.last_name;
        })


}

}
1个回答

6

设置您的工厂以使用 .then 并返回数据,如下所示:

casenoteApp.factory('MyFactory', function ($http) {
    var urlBase = 'http://xxxxxx/api/Client';

    return {
        getClients: function (userLogin) {
            return $http.get(urlBase + '/' + userLogin).then(function(data) {
                return data.result;
            });
        }
    };
});

你的控制器代码:

MyFactory.getClients(01234).then(function(data) {
    console.log(data); //hello data!
});

这导致了同样的问题。JSON返回看起来很好:{"int_id":123456,"last_name":"Doe","first_name":"John","type":"FAM","sex":null,"birthdate":null在fiddler中,但在控制台中我得到以下内容:XMLHttpRequest for http://xxxxxx/api/Client/192524需要跨源资源共享(CORS)。Web服务在同一服务器上,但在不同的虚拟目录中。这不应该需要jsonp,对吗?如果是这样,这听起来像是问题吗?为什么会出现这个错误? - Aaron Lind
好的,得清理一下头脑。当我开始这个项目时,Angular Visual Studio项目正在运行内置服务器,而Web服务已经托管,因此导致了跨源问题。现在我已将其重新托管到IIS上,并且当回调到我的控制器时,但是在将数据提交到console.log后仍然返回未定义。 - Aaron Lind
好的,现在它可以工作了。应该是“.data”,所以对于上面的数据,“data.data”现在返回结果。谢谢。 - Aaron Lind

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接