我有服务:
angular.module('app1App')
.service('Fullcontactservice', function Fullcontactservice(Restangular, $http, $q) {
// AngularJS will instantiate a singleton by calling "new" on this function
var self = this;
self.apiKey = "..........."
self.route = "person"
self.getProfile = function(email){
console.log("called")
console.log(email)
Restangular.one("person").get({email: email, apiKey: self.apiKey})
.then(function(response){
console.log(response)
return response
})
}
return self;
});
Controller :
angular.module('app1App')
.controller('FullcontactCtrl', function ($scope, Fullcontactservice) {
$scope.searchFullcontact = function(){
$scope.data = Fullcontactservice.getProfile($scope.email)
}
});
当我调用 searchFullcontact() 时,Restangular 会调用 fullcontact 并返回数据,但不会将其推送到作用域 - 我理解原因。当我使用 promises 时,只会生成 {}
并且不会推送任何数据。
我怎样才能让它这样做。我试图避免在我的 Controller 中使用 .then()
函数以使其保持 slim ,因为传统上我有非常大的 Controller 。
谢谢!
最佳答案
Restangular 有一个方便的功能,可让您使此代码正常工作:
self.getProfile = function(email){
return Restangular.one("person").get({email: email, apiKey: self.apiKey}).$object
}
$object
是一种有效的快捷方式,Restangular 首先创建一个空对象,一旦 REST 调用可用,该对象就会被填充。在 Controller 中使用 $scope.data
的代码必须灵活地处理最初为空的对象。如果您在模板 (html) 中使用 data
,这通常不是问题,因为 Angular 可以优雅地处理缺失(未定义)。
关于angularjs - 重新服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25439810/