Force HTTP interceptor in dynamic ngSrc request

后端 未结 4 1099
一整个雨季
一整个雨季 2020-12-03 03:53

I\'ve created an AngularJS application that loads images from an OAuth secured backend. My OAuth library is configured by adding an extra interceptor to the Angular $h

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-03 04:13

    Based on Michal's answer the directive could look like the below

    app.directive('httpSrc', [
            '$http', function ($http) {
                var directive = {
                    link: link,
                    restrict: 'A'
                };
                return directive;
    
                function link(scope, element, attrs) {
                    var requestConfig = {
                        method: 'Get',
                        url: attrs.httpSrc,
                        responseType: 'arraybuffer',
                        cache: 'true'
                    };
    
                    $http(requestConfig)
                        .then(function(response) {
                            var arr = new Uint8Array(response.data);
    
                            var raw = '';
                            var i, j, subArray, chunk = 5000;
                            for (i = 0, j = arr.length; i < j; i += chunk) {
                                subArray = arr.subarray(i, i + chunk);
                                raw += String.fromCharCode.apply(null, subArray);
                            }
    
                            var b64 = btoa(raw);
    
                            attrs.$set('src', "data:image/jpeg;base64," + b64);
                        });
                }
    
            }
        ]);
    

    You would then use it as follows

    
    

提交回复
热议问题