AngularJS Data Structure: Client side or API?

I have a prototype solution in AngularJS and it is working with the following data structure:

$scope.clients = [
    { client:"Client1", projects:[ 
        { project: "Project1", items:[
            { item: "This is the first item" },
            { item: "This is the second item" }
        ]},
        { project: "Project2", items:[
            { item: "This is the third item" },
            { item: "This is the fourth item" }
        ]}
    ]},
    { client:"Client2", projects:[ 
        { project: "Project4", items:[
            { item: "This is the fifth item" },
            { item: "This is the sixth item" }
        ]}
    ]}
];

I am looking to implement the back end and I am not sure if the API should serve the above nested data structure to the client or if it should serve a flat structure of items and then the AngularJS client app then creates the nested structure. Here is an example of the flat structure that the API would serve:

[
    { client: "Client 1", project: "Project 1", item: "This is the first item." },
    { client: "Client 1", project: "Project 1", item: "This is the second item.", },
    { client: "Client 1", project: "Project 2", item: "This is the third item.", },
    { client: "Client 2", project: "Project 4", item: "This is the fourth item.", }
];

What is the best approach for this? Additionally, is there any good references to for API design?


I generally find it helpful to not be translating my API responses to different formats throughout my application. If the nested structure is useful on your page, and it will continue to be useful elsewhere as well, I would just stick with it. You don't want to be in a situation where you are transforming an API response from one format to another on every page you use it on, so go with something that is cohesive, and simple to understand.

IMO, the nested structure looks better because you don't have to make groupings and associations on the front end. I tend to prefer when my API responses require very little if any "massaging" to work within the context of my page, if possible.

As far as API design goes, if you are looking for some standards this question's answer has some good references for standard API designs and response formats.


If you're working with JSON, then the "application/hal+json" standard is definitely worth looking at.

You can read all details right here: http://tools.ietf.org/html/draft-kelly-json-hal-05

There is also a very good presentation by Matthew Weier O'Phinney with sample code on how to use this with a PHP backend: http://www.zend.com/en/resources/webinars/ (scroll down to the "Build RESTful ZF2 Applications" webinar).

Basically it is a set of conventions that allow linking and embedding of data within your response, which is exactly what you need here.

Hope that helps!

链接地址: http://www.djcxy.com/p/48066.html

上一篇: 如何在云终端中返回自定义错误代码?

下一篇: AngularJS数据结构:客户端还是API?