在服务中使用Restangular

时间:2014-08-22 04:56:19

标签: angularjs restangular

我有服务:

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;

  });

控制器:

angular.module('app1App')
  .controller('FullcontactCtrl', function ($scope, Fullcontactservice) {


    $scope.searchFullcontact = function(){

        $scope.data = Fullcontactservice.getProfile($scope.email)
    }


  });

当我调用searchFullcontact()时,Restangular调用fullcontact并返回数据但是没有被推到范围内 - 我理解为什么。当我使用promises时,只有结果{}并且没有数据被推送。

我怎么能这样做呢。我试图避免我的控制器中的.then()功能,以保持它的纤薄,因为传统上我有非常大的控制器。

谢谢!

1 个答案:

答案 0 :(得分:3)

Restangular有一个方便的功能,允许你使这段代码工作:

self.getProfile = function(email){
    return Restangular.one("person").get({email: email, apiKey: self.apiKey}).$object
}

$object实际上是一个快捷方式,其中Restangular首先创建一个空对象,该对象在REST调用可用后填充其中的数据。在控制器中使用$scope.data的代码必须灵活处理最初为空的对象。如果您在模板(html)中使用data,因为角度优雅地处理缺失(未定义),这通常不是问题。