5

Using Angular JS's $resource service, is there a way to specify the If-None-Match and ETag headers for the 2nd, 3rd, etc polls of a resource?

    var SummarySearch = $resource(<<apiurl>>,
        { },
        {
            get: {
                method: 'GET',
                headers: {
                    'x-header': 'id'
                }
            }
        });

I've gotten this to work for setting a constant header (it's just x-header: id in this case), but I need something that varies per request, based on the ETag I last saw.

Update:

transformRequest looked promising, but I don't have access to the data that I initiated the request with, or the URL where that data ended up. As far as I can tell I only have access to the body I'd be POSTing (undefined in my case since I'm doing a GET) and the headersGetter function.

Trey Mack
  • 4,215
  • 2
  • 25
  • 31

1 Answers1

4

I discovered that $resource handles ETags on its own.

I hadn't implemented the server side of things when I posted this question. I set up If-None-Match handling server side figuring I'd have to just use the $http service on the client, but tried it out with my existing $resource .get call and it handles setting up the If-None-Match header automatically after my first poll of the resource.

I am reusing the 1 instance that $resource returned during setup.

Edit

AND I have the real-deal jQuery instead of jqLite. That's where If-None-Match seems to be set.

    // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
    if ( s.ifModified ) {
        ifModifiedKey = ifModifiedKey || s.url;
        if ( jQuery.lastModified[ ifModifiedKey ] ) {
            jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
        }
        if ( jQuery.etag[ ifModifiedKey ] ) {
            jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
        }
    }
Trey Mack
  • 4,215
  • 2
  • 25
  • 31
  • Can you point to some documentation that shows that `$resource` automatically sends `If-None-Match` headers? Everything else I've read suggests that it does not... Even searching the [source for ngResource](https://github.com/angular/angular.js/blob/master/src/ngResource/resource.js) for "If-None-Match" (and variants) yields nothing – rinogo Aug 19 '16 at 23:22
  • @rinogo Thanks for the question. I did a little more digging and updated the answer. – Trey Mack Aug 20 '16 at 02:32
  • AH. Got it. Thank you! So, it looks like it has less to do with ngResource and maybe more to do with jQuery? – rinogo Aug 20 '16 at 06:02