Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query all of something using $resource in AngularJS

I'm not convinced that I understand how to properly use Angular's services. I'm using a JAX-RS server-side.

If services are supposed to work like (as taken from the phonecat example)...

angular.module('workstation.services', ['ngResource']).
    factory('WorkflowService', function($resource, apiUrl){
        return $resource(apiUrl+'/api/workflow/:uuid', {uuid:'@uuid'}, {});
    });

Then how do I query for all workflows? I can't use the WorkflowService to accomplish that because it's already tried to /api/workflow/:uuid. I would need to have another service which is based around another URL.

This doesn't seem like it's very flexible, unless I'm using it wrong.

I'm used to seeing a Service handle all querying for data and have methods like WorkflowService.getActiveWorkflows() to return Workflow[]

However I'm not sure how to organize this service because I still want to have methods that interact with a single entity, like WorkflowService.save(workflow);. With how $resources are designed to be around a specific RESTful URL it's tough to structure that correctly...

like image 644
Webnet Avatar asked Apr 16 '13 16:04

Webnet


1 Answers

Check the angular documentation from $resource, read the actions arguments. It supports to define a url that will override the base url for a specific action.

Using a default action 'queryAll' you can query all of something from a resource.

Example:

angular.module('workstation.services', ['ngResource']).
factory('WorkflowService', function($resource, apiUrl){
    return $resource(apiUrl+'/api/workflow/:uuid', {uuid:'@uuid'}, {
        queryAll: {
            url: apiUrl + '/api/workflow/getAllActive',
            method: 'GET',
            cache: false,
            isArray: true
        }
    });
});
like image 66
josketres Avatar answered Nov 11 '22 05:11

josketres