首页 > 解决方案 > 通过 HttpRequest 加载安全缓存的图像

问题描述

我一直在寻找两个小时如何解决这个问题:

在 Angular 8.2.6 中,出于某些图像缓存的原因,我需要通过 HTTP 拦截器添加标头,因此我需要通过 HTTP 请求来请求图像:

this.http.get('ttps://1048665290.rsc.cdn77.org/thumbnails/MY-60-B.jpg', { responseType: 'arraybuffer' })
   .subscribe(res => {
        console.log(typeof res);
        const blob = new Blob([res]);
        this.image = this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(blob));
   });

一切似乎都很好,但由于某种原因,结果的类型是 Object 而不是 ArrayBuffer 或 Blob,因此 @angular/HttpClient 中有一段代码会引发错误:

case 'arraybuffer':
    return res$.pipe(map(function (res) {
        // Validate that the body is an ArrayBuffer.
        if (res.body !== null && !(res.body instanceof ArrayBuffer)) {
            throw new Error('Response is not an ArrayBuffer.');
        }
        return res.body;
    }));
case 'blob':
    return res$.pipe(map(function (res) {
        // Validate that the body is a Blob.
        if (res.body !== null && !(res.body instanceof Blob)) {
            throw new Error('Response is not a Blob.');
        }
        return res.body;
    }));
case 'text':
    return res$.pipe(map(function (res) {
        // Validate that the body is a string.
        if (res.body !== null && typeof res.body !== 'string') {
            throw new Error('Response is not a string.');
        }
        return res.body;
    }));

所以......问题是:我怎样才能加载它而不会出现这个错误?

因为我不知道如何将图像/jpeg 的文本版本转换为 ArrayBuffer 或 Blob。

问题可能出在 CDN 服务器上吗?

提前致谢。

标签: angularangular-universal

解决方案


推荐阅读