MChan
MChan

Reputation: 7162

AngularJS returning a promise causing 'then' of undefined

I have the following code as part of my AngularJS app:

myApp.factory('NewContactData', function($http,$log, $q) {
 return {    
   saveContact: function(contact){
     var deferred = $q.defer();  
     ...
     ...
     return deferred.promise;     
   }, 
   getContacts: function(){
     var gcdeferred = $q.defer();  
     ...
     ...
     return gcdeferred.promise;         
   }      
 }; 
});      

When I try to call getContacts from my app controller as follows:

myApp.controller('ContactsController',
        function ContactsController($scope, $location, NewContactData){


    NewContactData.getContacts().$promise.then(
            function(response){
               console.log(response);
            },
            function(status){
               console.log(status);
            }
    );         

I get error:

TypeError: Cannot call method 'then' of undefined
 at new ContactsController

Even though as it is shown from my code that getContacts return promise. Can someone please tell me what I am missing here? Thanks

Upvotes: 2

Views: 8202

Answers (2)

Ye Liu
Ye Liu

Reputation: 8976

Try this:

NewContactData.getContacts().then(
        function(response){
           console.log(response);
        },
        function(status){
           console.log(status);
        }
);  

Upvotes: 1

doodeec
doodeec

Reputation: 2927

it's just NewContactData.getContacts().then( since you are already returning a promise

Upvotes: 2

Related Questions