Aar*_*ind 3 angularjs angular-services
工厂restful web api调用后,角度控制器结果未定义.我看过很多关于这个的帖子,但似乎都没有解决我的问题.我有一个控制器,可以进行一次宁静的web api2调用.使用fiddler我可以看到调用和200响应,但我似乎永远无法得到结果,我知道get是通过异步.以下是工厂和控制器.我也尝试将回调显式发送到工厂,这种方法甚至不会导致未定义的对象结果,只是不起作用.我真的处于停滞状态,我是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;
})
}
}
Run Code Online (Sandbox Code Playgroud)
设置工厂使用.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;
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
而你的控制器:
MyFactory.getClients(01234).then(function(data) {
console.log(data); //hello data!
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3378 次 |
| 最近记录: |