Sending ETag with $resource

2019-05-01 14:58发布

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.

1条回答
我命由我不由天
2楼-- · 2019-05-01 15:26

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 ] );
        }
    }
查看更多
登录 后发表回答