2016-08-25 99 views
0

您好我不明白爲什麼總是我從這項服務中獲得空數組時,我的控制器返回值從角服務

angular 
.module('dimecuba.services', []) 
.factory('Contacts', function($cordovaContacts, $ionicPlatform) { 

    var contactsFound = []; 

    var contacts = { 
     all:function(){ 
      var options = {}; 
      options.multiple = true; 
      options.filter = ""; 
      //options.fields = ['displayName']; 
      options.hasPhoneNumber = true; 
      $ionicPlatform.ready(function(){ 
       $cordovaContacts.find(options).then(
        function(allContacts){ 
         angular.forEach(allContacts, function(contact, key) { 
          contactsFound.push(contact); 
         }); 
         console.log("Contacts Found:" + JSON.stringify(contactsFound)); 
         return contactsFound; 
        }, 
        function(contactError){ 
         console.log('Error'); 
        } 
       ); 
      }); 
     } 
    }; //end contacts 
    console.log("Contacts:"+JSON.stringify(contacts)); 
    return contacts; 
}); 
+0

顯示$ cordovaContacts和$ ionicPlatform包含的內容。你注射這些服務? –

+0

目標是return contactsFound ...我可以如何修復此代碼返回contacstFound – icemandev

+0

看起來您正在返回「contacts」而不是'contactsFound'。在'contacts'中聲明'contactsFound'並再次嘗試 –

回答

0

使用return援引承諾。需要在每個嵌套級別包含return聲明。

app.factory('Contacts', function($cordovaContacts, $ionicPlatform) { 

    var contacts = { 
     all:function(){ 
      var options = {}; 
      options.multiple = true; 
      options.filter = ""; 
      options.hasPhoneNumber = true; 
      //return promise 
      return $ionicPlatform.ready().then(function() { 
       //return promise to chain 
       return $cordovaContacts.find(options) 
      }).then(function(allContacts){ 
       var contactsFound = []; 
       angular.forEach(allContacts, function(contact, key) { 
        contactsFound.push(contact); 
       }); 
       //return to chain data 
       return contactsFound; 
      }).catch(function(contactError){ 
       console.log('Error'); 
       //throw to chain error 
       throw contactError; 
      }); 
     } 
    }; //end contacts 

    return contacts; 
}); 

在控制器中,使用返回的promise。

app.controller("myCtrl", function($scope,Contacts) { 

    var contactsPromise = Contacts.all(); 

    contactsPromise.then(function(contactsFound) { 
     $scope.contactsFound = contactsFound; 
    }); 
}); 
+0

使用'... ready()。然後(function(){return $ cordovaContacts.find(options);})來降低嵌套級別會更加優雅。然後(...)' –

+0

@JBNizet好點。查看更新的答案。 – georgeawg