Angularjs $resource not working with an array returned from a REST API

前端 未结 6 2153
失恋的感觉
失恋的感觉 2020-12-06 05:15

I am trying to learn angularjs, and have hit a block in trying to databind to an array returned from a Rest API. I have a simple azure api returning an array of person objec

6条回答
  •  生来不讨喜
    2020-12-06 05:55

    In order to handle arrays with the $resource service, it's suggested that you use the query method. As you can see below, the query method is built to handle arrays.

    { 'get':    {method:'GET'},
      'save':   {method:'POST'},
      'query':  {method:'GET', isArray:true},
      'remove': {method:'DELETE'},
      'delete': {method:'DELETE'} };
    

    The code you should use in order to return this array to your scope is

    angular.module("ToDoApp", ["ngResource"]);
    
    function TodoCtrl($scope, $resource) {
        var svc = $resource('http://testv1.cloudapp.net/test.svc/persons');
        $scope.items = svc.query();
        $scope.msg = "Hello World";
    }
    

    This assumes that your REST API is working and will return an array.

    For further reading head to the docs

    http://docs.angularjs.org/api/ngResource.$resource

提交回复
热议问题