简体   繁体   中英

Angular - Generic image service vs resource-specific (e.g., user, image, animal) image services

I'm having a little trouble wrapping my mind around a problem and could use a little help.

I'm developing an app in Rails using Angular.js for my client-side MVC framework and have created a service by which Angular can get images. It's pretty straightforward:

var ImageServices = angular.module("ImageServices", ["ngResource"]);

ImageServices.factory("Image", ["$resource",
  function ($resource) {
    return $resource("/images/:id.json", {}, {
      "query"  : { method: "GET", params: {}, isArray: true },
      "update" : { method: "PUT", params: { id: "@id" } },
      "remove" : { method: "DELETE" }
    });
  }
]);

The above service is probably a bit too generic for my purposes. What I'd like for the service to provide me is all images associated with a given user . I suppose I could accomplish this by nesting the desired image data within the user's data, like this:

user = {
  // user attributes
  blah: "blah",
  //image objects
  images: [
    {} 
  ]
}

Or maybe I could somehow write code in Rails that will return all images associated with the user, thus:

http://localhost:3000/users/1/images.json

Or maybe I could just make a service for each type of data that I'd like returned to Angular.

Architecturally, I'm not sure what makes sense. Could someone provide some insight into what the best possible path might be? If there are no hard and fast answers, I'm not opposed to reading a book on the topic if you could recommend one. Thanks!

The $resource service is kind of like a wrapper for the $http service. It has methods built into it.

services.factory('Images', ['$resource',
     function($resource) {
     return $resource('/images/:id', {id: '@id'});
    }]);

The @id tells it to pick the id field from its object and use that as the id parameter. So in your case, you could do {id: '@user'}.

The above resource give you access to:

Images.get()    //GET Single JSON
Images.save()   //POST Single JSON
Images.query()  //GET JSON Array
Images.remove() //DELETE Single JSON
Images.delete() //DELETE Single JSON

Images.get({id: 15}) //will make return all images for a user through a call to /images/15.

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