AngularJS: Creating Objects that map to REST Resources (ORM-Style)

前端 未结 7 702
南笙
南笙 2021-01-29 18:09

I\'m pretty new to AngularJS, but I\'m pretty unclear on how to tie it up to my Server\'s REST Api backend.

For example, say I have an \"image\" resource that I get by G

7条回答
  •  北恋
    北恋 (楼主)
    2021-01-29 18:26

    One more example of helper for ngResource. This relies on fact that the vast majority of services is something like that:

    http://host/api/posts
    http://host/api/posts/123
    http://host/api/posts/123/comments
    http://host/api/posts/123/comments/456
    

    So, the task is to make a helper that create AngularJS resource objects that maps on such services. Here it is:

    'use strict';
    
    var api = angular.module('api', ['ngResource']);
    
    // RESTful API helper
    api.addService = function (serviceNameComponents) {
        var serviceName = "";
        var resource = "/api"; // Root for REST services
        var params = {};
    
        serviceNameComponents.forEach(function (serviceNameComponent) {
            serviceName += serviceNameComponent;
    
            var lowerCaseServiceNameComponent = serviceNameComponent.toLowerCase();
            var collection = lowerCaseServiceNameComponent + 's';
            var id = lowerCaseServiceNameComponent + 'Id';
    
            resource += "/" + collection + "/:" + id;
            params[id] = '@' + id;
        });
    
        this.factory(serviceName, ['$resource',
            function ($resource) {
                return $resource(resource, {}, {
                        query: {
                            method: 'GET',
                            params: params,
                            isArray: true
                        },
                        save: {
                            method: 'POST',
                        },
                        update: {
                            method: 'PUT',
                            params: params,
                        },
                        remove: {
                            method: 'DELETE',
                            params: params,
                        }
                    }
                );
            }
        ]);
    }
    

    So, to use it simply call this helper

    api.addService(["Post"]);
    api.addService(["Post", "Comment"]);
    

    And then you can use Post and PostComment in code with needed params like :post_id

提交回复
热议问题