本文介绍了通过HTTP拦截拦截IMG-SRC,以及不输于不断变化它的能力的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下需求:

1),我希望能够通过我的HTTP拦截器拦截对 IMG NG-SRC 来电。由于NG-SRC不会被路由到http拦截器,我使用此http-SRC指令http://stackoverflow.com/a/29606436/1361529

1) I'd like to be able to intercept calls to img ng-src via my http interceptor. Given that ng-src does not get routed to http interceptors, I am using this http-src directive http://stackoverflow.com/a/29606436/1361529

2)但问题是,这个指令只能使用一次 - 它取代了src属性与图像,所以图像只读取一次,并不会改变。

2) The problem however is that this directive only works once - it replaces the "src" attribute with the image, so the image only loads once and does not change.

我的意思是我的模板具有以下code:

What I mean is my template has the following code:

<span ng-repeat="monitor in MontageMonitors>
<img id="img-$index" http-src="{{LoginData.streamingurl}}/nph-zms?mode=single&monitor={{monitor.Monitor.Id}}&scale={{LoginData.montageQuality}}{{$root.authSession}}&rand={{$root.rand}}" ng-click="openModal(monitor.Monitor.Id, monitor.Monitor.Controllable, monitor.Monitor.ControlId)" />

</span>

此图像通过重装定时器每1秒在我的code,但由于HTTP-SRC指令本质上与内嵌图像替换src属性,它不会更新。

This image is reloaded every 1 second via a timer in my code, but since the http-src directive essentially replaces the src attribute with an inline image, it doesn't update.

我该如何解决这个问题?

How do I solve this?

感谢

推荐答案

在自定义的 HTTP-SRC 指令的链接功能,您将需要$观察属性,使你的$ HTTP调用它每次更改时间。

In your custom http-src directive's link function, you would need to $observe the attribute and make your $http call each time it changes.

像这样的东西(基于从SO回答您链接到code):

Something like this (based on the code from the SO answer you linked to):

angular.module('myApp', [])
  .directive('httpSrc', httpSrcDirective);

httpSrcDirective.$inject = ['$http'];

function httpSrcDirective($http) {
  return {
    link: postLink,
    restrict: 'A'
  };

  function postLink(scope, element, attrs) {
    var requestConfig = {
      method: 'GET',
      responseType: 'arraybuffer',
      cache: 'true'
    };

    function base64Img(data) {
      var arr = new Uint8Array(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);
      }
      return btoa(raw);
    };

    attrs.$observe('httpSrc', function(newValue) {
      requestConfig.url = newValue;
      $http(requestConfig)
        .then(function(data) {
          attrs.$set('src', "data:image/jpeg;base64," + base64Img(data));
        });
    });
  }
}

这篇关于通过HTTP拦截拦截IMG-SRC,以及不输于不断变化它的能力的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 05:52