angularjsparametersangular-resource

$resource URL with in-path parameter


I have the following method in a service:

function getMyData() {
    if (service.myData === NULL) {
        service.myData = $resource(API.MY_DATA, {}).query();
    }
    return service.myData;
}

API.MY_DATA = '/path1/path2/path3/:myparam'

:myparam parameter will be an integer representing an id that the back-end will need to use in order to perform the appropriate query to return what is being requested by a GET request.

Question: How do I pass this parameter in my getMyData method appropriately so it resolves to something like:

/path1/path2/path3/568?


Solution

  • function getMyData() {
       if (service.myData === NULL) {
           var api = $resource(API.MY_DATA, {}); 
           service.myData = api.query({'myparam', value}); 
       }
       return service.myData;
     }
    

    I would suggest you to create a factory so then you can reuse the service instead of recreate every time you need to use it. This way you only need to inject the factory/service.

    .factory("apiService", ['$resource', function($resource){
      return $resource( url, null, {extra api call if need}); 
    }