Restorative in service

I have a service:

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


  });

      

When I call searchFullcontact (), Restangular calls fullcontact and returns the data, but it is not in scope - I understand why. When I use promises, just the results are for {}

and no data is pushed.

How can i do this. I am trying to avoid the function .then()

inside my controller to keep it thin, because traditionally I have had very large controllers.

Thank!

+3


source to share


1 answer


Restangular has a handy function to do this code:

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

      



$object

is effectively a shortcut where Restangular first creates an empty object that is populated with data from the REST call when available. Code working from $scope.data

within your controller needs to be flexible to handle an initially empty object. This is usually not a problem if you are using data

inside a template (html) as angular handles the missing (undefined) gracefully.

+3


source







All Articles