简体   繁体   中英

Angular JS: Get subproperty from service response

I am just starting out with Angular and trying to adapt a tutorial I have been following.

I have a resource defined as:

.factory('Session', function ($resource) {
    return $resource('http://localhost/api/sessions');
});

I am trying to use the response with a controller like this:

.controller('SessionsCtrl', function($scope, Session) {
    $scope.sessions = Session.query();
})

The problem I am coming up against is the format of the JSON response has the sessions in a subproperty as such:

{
  sessions: [
    {
      id: 1,
      title: "Welcome"
    {
      id: 2,
      title: "Session 1"
    }
  ]
}

How do I get the resource to look as the sessions property?

If your service is sending an object instead of an array, you should add isArray: false to its declaration:

yourApp.factory('Session', function ($resource) {
    return $resource(
        'http://localhost/api/sessions',
        {},
        {'query': {method: 'GET', isArray: false }}
    );
});

In your controller you can use a callback :

yourApp.controller('SessionsCtrl', function($scope, Session) {
    $scope.sessions = Session.query(function(result) {
         return result.sessions;
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM