gpt4 book ai didi

AngularJS Controller /工厂返回 undefined object

转载 作者:行者123 更新时间:2023-12-03 08:09:20 25 4
gpt4 key购买 nike

在工厂 restful web api 调用后, Angular Controller 结果未定义。我看过很多关于这个的帖子,但似乎没有一个能解决我的问题。我有一个 Controller 可以进行 Restful 网络 api2 调用。使用 fiddler 我可以看到调用和 200 响应,但我似乎永远无法获得结果,而且我知道获取是通过异步进行的。下面是工厂和 Controller 。我也尝试过将回调显式发送到工厂,这种方法甚至不会导致 undefined object 结果,只是行不通。我真的在这里停滞不前,我是 Angularjs 的新手,怎么了?目前,我将 Controller 调用连接到一个按钮以进行显式测试。

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


}

}

最佳答案

将您的工厂设置为使用 .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;
});
}
};
});

还有你的 Controller :

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

关于AngularJS Controller /工厂返回 undefined object ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25186690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com