如何使用 Angular 拦截器和管道来获取需要基本身份验证标头的图像的 http 请求

Tin*_*say 8 angular-material angular

我正在尝试使用 Angular 拦截器和管道通过将图像 src 的基本授权标头传递到远程服务器来访问图像。我正在使用 .json 文件形式的图像路径。它对我不起作用,因为我可能错过了一些东西。

当我从变量获取图像路径时,我不确定如何在图像 src 标记中提供管道名称。

** src="image.imagePath |安全| 异步" **

谁能帮我解决这个问题吗?主要目的是访问远程服务器上存在的图像,这需要角度 UI 中的基本授权。

auth.interceptor.ts

import { Injectable } from '@angular/core';
import {  HttpRequest,  HttpHandler,  HttpEvent,  HttpInterceptor} from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

      request = request.clone(
        {setHeaders: {'Authorization': 'Basic ' + btoa('username:password')}
      });
      
    console.log('processing request', request);
      return next.handle(request);
  }
}
Run Code Online (Sandbox Code Playgroud)

安全.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Pipe({
  name: 'secure'
})
export class SecurePipe implements PipeTransform {
  constructor(private http: HttpClient, private sanitizer: DomSanitizer) { }

  transform(url): Observable<SafeUrl> {
    return this.http
      .get(url, { responseType: 'blob' })
      .pipe(map(val => this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(val))));
  }

}
Run Code Online (Sandbox Code Playgroud)

应用程序组件.html

<p-orderList [value]="images" [listStyle]="{'height':'450px'}"  filterBy="tag"
  filterPlaceholder="Filter by Tag" dragdrop="true">
  <ng-template let-image pTemplate="item">
    <div class="ui-helper-clearfix">
      <img src="image.imagePath |secure| async" width="100">
      <div  style="font-size:20px;float:right;margin:15px 5px 0 0"><b>{{image.tag}}</b>-{{image.description}}.
        <b>Year</b>-{{image.year}}</div>
    </div>
  </ng-template>
</p-orderList>
Run Code Online (Sandbox Code Playgroud)

图像-small.json

data": [
        {
            "imagePath": "https:someserver/wp2919299.jpg",
            "tag": "tmp",
            "description": "tag1, tag2, tag3",
            "year": 2010
        },
        {
            "imagePath": https:someserver/wp21123299.jpg",
            "tag": "tmp2",
            "description": "tag1, tag2",
            "year": 2011                
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

用户界面看起来像这样在此输入图像描述

小智 0

管道用于通过角度http客户端进行请求,图像src是html默认操作,它不会使用角度http客户端,您必须通过http客户端加载图像数据