2014-10-30 124 views
1

我是一個離子/有角度的n00b,我無法繞着我的頭圍繞如何做到這一點。如何在Angular中的工廠方法中返回數據?

我廠擁有這樣定義:

angular.module('starter.services', []) 

.factory('Calendars', function() { 

    var calendars; 
    var success = function(message) { 
     calendars = message; 
     return calendars; 
    }; 
    var error = function(message) {alert("Error: " + message)}; 

    window.plugins.calendar.listCalendars(success,error); 

    return { 
     all: function() { 
      return calendars; 
     }, 
     get: function(calendarId) { 
      return calendars[calendarId]; 
     } 
    } 


}); 

我試圖找回這樣我的控制器內的日曆:

.controller('CalendarsCtrl', function($scope,Calendars) { 

    $scope.calendars = Calendars.all(); 

}) 

工廠方法被調用,但結果在'成功'回調被調用之前不可用,所以CalendarsCtrl總是未定義的。

如何解決這個問題?

編輯 - 我已更正控制器內的呼叫。儘管如此,該函數在成功回調之前不會返回結果。

+1

我注意到你沒有在'success'回調之外定義'calendars'。但即使你這樣做,你應該檢索你的控制器中的日曆'$ scope = Calendars.all()' – Blazemonger 2014-10-30 15:13:19

回答

0

角度工廠正在返回一個對象,爲了調用他們的方法,您必須使用Calendar.all()調用它們來調用內部函數。

2

您將不得不使用承諾。

首先添加的依賴$ Q

.factory('Calendars', function ($q) { 

然後在所有的()這樣做

all: function() { 
    var deferred = $q.defer(); 

    window.plugins.calendar.listCalendars(function(data) { 
     deferred.resolve(data); 
    } 
    ,function(error) { 
     deferred.reject(error); // something went wrong here 
    }); 
    return deferred.promise; 

現在這將使返回後的數據已經解決了(沒有更多的不確定)。

最後一件事,現在,當你得到的數據傳回在你的控制器,你這樣做

var promise = Calendars.all(); 
promise.then(function(data) { 
    console.log('Success: you can use your calendar data now'); 
}, function(error) { 
    console.log('Failed for some reason:' + error); 
}); 

你可以閱讀一些有關承諾這裏:https://docs.angularjs.org/api/ng/service/ $ Q

我知道這很難把握第一次。