AngularJS: using $ http interceptors and OAuth tokens when using ng-src directive

I am creating a Cordova / Phonegap application that communicates with a Rails server via a JSON API that uses OAuth.

I already have a lot of button-driven functionality and I use an HTTP interceptor to look up server responses 401 Unauthorized

, which asks for new OAuth tokens and then repeats the same request.

My solution is based on this code: https://github.com/witoldsz/angular-http-auth

But I can't see how to do all this when getting images through <img ng-src="image/url">

.

So my question is twofold:

1 How can I inject an OAuth token into a request ng-src

?

2How to intercept 401 responses to refresh authorization token and retry requests?

+3


source to share


2 answers


Vasco! How are you?

I used an approach similar to that used in this link: https://github.com/dougmoscrop/angular-img-http-src/blob/master/index.js

I added parts of this to my controller:

function SampleCtrl($scope, $http) {
    $scope.ImageUrl = '';

    // this method can be on a service ($http or $resource)
    $scope.getImageService = function (imageId) {
        return $http.get('../MyApi/MyAction/', {
            responseType: 'arraybuffer',
            params: { id: imageId }
        });
    };

    // this will be called when you need to load the image
    $scope.loadImage = function(imageId)
    {
        $scope.getImageService(imageId).then(function (response) {
            var imageBlob = new Blob([response.data], { type: response.headers('Content-Type') });
            $scope.ImageUrl = (window.URL || window.webkitURL).createObjectURL(imageBlob);
        });
    };

    $scope.loadImage('image_001');
}

      



And the html will look like this:

<img ng-src="{{ImageUrl}}" alt="alternate" title="title" />

      

By doing this, the interceptor will handle the http get and include the header with the OAuth token.

+1


source


To answer both questions, you need an HTTP interceptor that will 1) set an Oauth token on all incoming requests and 2) fix 401 errors and allow them for you, update and set authentication tokens if and when needed.

Check out a great post on how to do this. Also read AngularJs' insightful documentation on $ http interceptors . Everything is.



I really hope they help you. Best.

0


source







All Articles