我有以下 Controller 代码
module.registerController('DemoCtrl', function ($scope, myFactory) {
myFactory.get(function (data) {
console.log(data); /// data is always undefined
});
});
并跟随调用restful webapi的工厂
module.registerFactory('myFactory', ['$http',
function ($http) {
function get(callback) {
$http.get('mywebapiurl')
.success(function (response) {
//debugger; data comes back from server
callback(response);
}).error(function (response, status, headers, config) {
callback(response);
});
}
return {
get: get
}
}]);
工厂正在调用 webapi 服务并获取数据。但是在 Controller 中,数据不会返回。
我在这里遗漏了一些明显的东西吗?也不确定这是否是使用工厂在 Controller 中调用 angularjs 中的 web 服务的最佳方式。欢迎任何意见。
谢谢
最佳答案
您想要返回 promise而不是传递回调。由于 $http.get 已经返回一个 Promise,您可以直接返回该 Promise,或者直接返回响应数据的派生 Promise。顺便说一句,您的工厂
看起来应该是一个服务
:
angular.moudule('yourApp')
.service('myService', ['$http', myService]);
function myService($http) {
this.get = function(url) {
return $http.get(url)
.then(function transformData(response){
return response.data;
}).catch(function onError(rejectionResponse){
//Whatever you want to do here
});
}
}
这样 myService.get
将返回一个 Promise,您可以使用 .then()
、.catch()
和 .finally ()
你想要什么,保持框架编码风格。例如:
var squirrels = [];
myService.get('http://squirrelshop.com/api/squirrels')
.then(function(squirrelsData){
console.log('Got the squirrels!');
squirrels = squirrelsData;
}).catch(function(rejection){
console.warn('Couldnt fetch squirrels. Reason: ' + rejection);
});
关于javascript - 在 angularjs 中调用 http (RESTFUL WebAPI) 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31982019/