1

我敢肯定這件事情簡單,我在這裏失蹤,但我不能得到這個工作.. 我想用一個工廠,這樣我可以重複使用多個控制器的數據。不能得到restangular工廠上班

(function() { 
'use strict'; 

angular 
    .module('www') 
    .factory('profileFactory', profileFactory); 

profileFactory.$inject = ['Restangular']; 

/* @ngInject */ 
function profileFactory(Restangular) { 

    var service = { 
     getUserData: Restangular.one('/user/profile/').getList(), 
     getFriendList: Restangular.all('api/users/getfriendsinvitations/').getList() 
    }; 
    return service; 

    } 
})(); 

控制器:

(function() { 
    'use strict'; 

    angular 
     .module('www') 
     .controller('ProfileController', ProfileController); 

    ProfileController.$inject = ['profileFactory']; 

    /* @ngInject */ 
    function ProfileController() { 

     activate(); 

     function activate(profileFactory, $scope) { 
     profileFactory.getFriendList.then(function (homeFriends) { 
     $scope.homeFriends = homeFriends; 
     }); 
     } 
    } 
})(); 

而且我不斷收到 「類型錯誤:無法讀取的未定義的屬性 'getFriendList'」

編輯:我曾嘗試爲好,https://github.com/mgonto/restangular#decoupled-restangular-service,但沒有運氣!

+0

請形成你的標題一個實際的問題。它看起來像標籤。另外,請擴展您自己解決這個問題的努力。你檢查過第一/第三方圖書館的文件嗎? – onebree

+0

你能提供一個plunker文件嗎?我們需要知道另一個細節,例如:「您撥打服務的方式」等。 –

回答

1

您的工廠沒有正確定義。爲了給服務使用者提供工廠函數,您應該在函數中定義工廠代碼,並返回該工具將幫助您繼續承諾鏈。

代碼

function profileFactory(Restangular) { 

    var service = { 
     getUserData: function(){ 
      return Restangular.one('/user/profile/').getList(); 
     }, 
     getFriendList: function(){ 
      return Restangular.all('api/users/getfriendsinvitations/').getList(); 
     } 
    }; 
    return service; 
} 

控制器

(function() { 
    'use strict'; 

    angular 
     .module('www') 
     .controller('ProfileController', ProfileController); 

    ProfileController.$inject = ['profileFactory', '$scope']; 

    /* @ngInject */ 
    function ProfileController(profileFactory, $scope) { //<==added dependancy here 

     activate(); 

     function activate() { 
     profileFactory.getFriendList().then(function (homeFriends) { 
     $scope.homeFriends = homeFriends; 
     }); 
     } 
    } 
})(); 
+0

使用此代碼獲取相同的錯誤..? – Mackelito

+0

另外,我發現這一點,http://stackoverflow.com/questions/22496041/angularjs-restangular-call-inside-factory-service,所以它看起來像它應該工作!(?) – Mackelito

+0

@Mackelito檢查我的更新答案..謝謝:) –

0

你必須注入控制器的功能,裏面的profileFactory服務。