简体   繁体   English

Angular JS:从服务响应中获取子属性

[英]Angular JS: Get subproperty from service response

I am just starting out with Angular and trying to adapt a tutorial I have been following. 我刚开始使用Angular并尝试调整我一直关注的教程。

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: 我要面对的问题是JSON响应的格式具有这样的子属性的会话:

{
  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: 如果您的服务是发送对象而不是数组,则应在其声明中添加isArray:false

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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