Search code examples
angularjsangular-resource

ng $resource Fails to Dynamically Generate URI


The Problem:

I have code to set up a $resource that seems to compile without error:

var ReportsRest = $resource('/reports/:reportId', {reportId: '@id'});
ReportsRest.get({id: 123});

but when that code actually executes the request url that is generated looks like this:

GET http://localhost:5523/reports?id=123 404 (Not Found)

The id is not being parsed and dynamically loaded into the URI. Is there something that I am missing?

Plunkr

http://plnkr.co/edit/3ikqMsnDI9r9LThaQLf3?p=preview


Solution

  • Try this:

    var ReportsRest = $resource('/reports/:reportId', {reportId: '@id'});
    ReportsRest.get({reportId: 123});
    

    Under $resource Usage, there is this block of text.

    paramDefaults

    Default values for url parameters. These can be overridden in actions methods. If any of the parameter value is a function, it will be executed every time when a param value needs to be obtained for a request (unless the param was overridden).

    Each key value in the parameter object is first bound to url template if present and then any excess keys are appended to the url search query after the ?.

    Given a template /path/:verb and parameter {verb:'greet', salutation:'Hello'} results in URL /path/greet?salutation=Hello.

    If the parameter value is prefixed with @ then the value for that parameter will be extracted from the corresponding property on the data object (provided when calling an action method). For example, if the defaultParam object is {someParam: '@someProp'} then the value of someParam will be data.someProp.

    To summarize, the object you pass in needs to use the key of your paramDefaults object to get the value. That value replaces the same :key text in your URL pattern. Any value in the paramDefaults object that is prefixed with an @ will be set on the returned model data as a property named whatever follows the @.

    var ReportsRest = $resource('/reports/:reportId', {reportId: '@id'});
    ReportsRest.get({
        reportId: 123,
        other: 123
    }, function(data) { /* ... */ });
    

    This makes a request to /reports/123?other=123. data, in the callback, looks like { id: 123 }.