2014-11-25 80 views
1

我有一個web API,它將List<KeyValuePair<string, byte>>返回給角度js工廠。我然後在選擇使用 - >在javascript中循環遍歷角度js數組

<select ng-model="survey.surveyType" class="form-control" id="surveyType"> 
        <option ng-repeat="surveyType in surveyTypes" value="{{surveyType.value}}">{{surveyType.key}}</option> 
       </select> 

這工作正常。角循環並正確顯示對象。當與web api方法交談時,我已經這樣配置 - >

app.factory('Survey', ['$resource', function ($resource) { 
return $resource('http://localhost:52133/api/surveyapi/:id', null, 
    { 
     'update': { method: 'PUT' }, 
     'getSurveyTypesAsDictionary': { method: 'GET', isArray: true, url: 'http://localhost:52133/api/surveyapi/GetSurveyTypesAsDictionary' } 
    }); 
}]); 

// fetching the values in my controller 
var surveyTypes = Survey.getSurveyTypesAsDictionary(); 

現在我的問題是這樣的。我無法循環結果。在控制檯物體看起來是這樣的 - >

enter image description here

但是,如果我試圖讓我的角度數組中的值有什麼都沒有。例如surveyTypes.length爲0.

問題。我如何使用JavaScript來使用數組? 謝謝!

編輯: 我想只有Dictionary<string, byte>從Web API返回,但我沒有得到它在所有的工作。

編輯,註釋的Sergiu:

var promise = Survey.getSurveyTypesAsDictionary(); 
promise.$promise.then(function (response) { 
    console.log(response.length); 
}); 

,使你的建議的工作,我不得不從對象獲取$promise。這是正確的還是我需要配置我的工廠,使其工作的方式,你的語法寫入?

+4

'getSurveyTypesAsDictionary'使一個_asynchronous_請求並返回一個_promise_。你需要使用'Survey.getSurveyTypesAsDictionary()。then(function(response){// response可以在這裏使用});'。 – 2014-11-25 14:12:00

+0

可能重複的[如何從Ajax調用返回響應?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – 2014-11-25 14:12:30

+0

謝謝Sergiu ,在編輯中提出了一個後續問題:) – Andreas 2014-11-25 14:27:10

回答

4

首先,返回的resource object具有提供高級行爲而不需要與低級別服務交互的操作方法。

例如

Post.query(function(data) { 
    $scope.posts = data; 
}); 

,或者還可以通過在物體上的$promise屬性訪問原始$http承諾返回

var req = Post.query().$promise; 
req.then(function(data) { 
    $scope.posts = data; 
});