簡體   English   中英

如何使用 Angular 攔截器和 pipe 為 http 獲取需要基本身份驗證的圖像請求 header

[英]How to use Angular Interceptors and pipe for http get request for images which require basic auth header

我正在嘗試使用 Angular 攔截器和 pipe 通過將圖像 src 的基本授權 header 傳遞到遠程服務器來訪問圖像。 我正在使用圖像路徑 form.json 文件。 它對我不起作用,因為我可能錯過了一些東西。

當我從變量獲取圖像路徑時,我不確定如何在圖像 src 標記中提供 pipe 名稱。

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

誰能幫我解決這個問題? 主要目的是訪問遠程服務器上的圖像,這需要 angular 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);
  }
}

安全.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))));
  }

}

app.component.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>

圖片-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                
        }
    ]
}

用戶界面看起來像這樣在此處輸入圖像描述

pipe is for request go through angular http client, and image src is a html default action, which will not use angular http client, you have to load the image data by http client

更改變換 function 如下所示:

async transform(src: string): Promise<string> {
    if (src.indexOf(';base64,') > -1) {
        return src;
    }
    const token = '[bearer token]';
    const headers = new HttpHeaders({ 'Authorization': `Bearer ${token}` });
    const imageBlob = await this.http.get(src, { headers, responseType: 'blob' }).toPromise();
    const reader = new FileReader();
    return new Promise((resolve, reject) => {
        reader.onloadend = () => resolve(reader.result as string);
        reader.readAsDataURL(imageBlob);
    });
}

使用[attr.src]=image.imagePath |secure| async [attr.src]=image.imagePath |secure| async

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM