1

I have a web api that returns List<KeyValuePair<string, byte>> to an angular js factory. I then present it in an select using ->

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

This works fine. Angular loops and displays the object correctly. When talking to the web api method I have configured it like this ->

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();

Now my problem is this. I can't loop the result. In the console the object looks like this ->

enter image description here

But if I try to get the values inside my angular array there's nothing there. For instance surveyTypes.length is 0.

Question. How can I consume the array using JavaScript? Thanks!

EDIT: I tried to return only Dictionary<string, byte> from the web api but I didn't get it to work at all.

EDIT, comment to Sergiu:

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

to make your suggestion work I have to get $promise from the object. Is this correct or do I need to configure my factory to make it work the way your syntax is written?

Andreas
  • 2,336
  • 2
  • 28
  • 45
  • 4
    `getSurveyTypesAsDictionary` makes an _asynchronous_ request and returns a _promise_. You need to use `Survey.getSurveyTypesAsDictionary().then(function(response) { // response can be used here });`. – Sergiu Paraschiv Nov 25 '14 at 14:12
  • possible duplicate of [How to return the response from an Ajax call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Sergiu Paraschiv Nov 25 '14 at 14:12
  • Thanks Sergiu, made a follow up question in the edit :) – Andreas Nov 25 '14 at 14:27
  • 1
    Yes, you can use the raw `$promise` object like that or you can use the _callback_ syntax as described in the docs: https://docs.angularjs.org/api/ngResource/service/$resource – Sergiu Paraschiv Nov 25 '14 at 14:34

1 Answers1

4

First off, the returned resource object has action methods which provide high-level behaviors without the need to interact with the low level $http service.

For example

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

or, you can also access the raw $http promise via the $promise property on the object returned

 var req = Post.query().$promise;
 req.then(function(data) { 
     $scope.posts = data;
 });
Andy Ecca
  • 1,929
  • 14
  • 14