7

I am trying to use Angular Interceptor and pipe for accessing images by passing a basic authorization header for images src to a remote server. I am using images path form .json file. It's not working for me as I may have missed something.

I am not sure how to provide a pipe name in image src tag when I am taking an image path from the variable.

** src="image.imagePath |secure| async" **

Can anyone please help me with this? The main intention is to access images present on a remote server which requires basic authorization in 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);
  }
}

secure.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>

image-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                
        }
    ]
}

UI look like this enter image description here

DevSay
  • 886
  • 1
  • 14
  • 32

3 Answers3

1

Use <img [attr.src]="image.imagePath | secure | async" width="100">. This will do the trick.

For more details see: https://stackoverflow.com/a/50463201/936752

m1ld
  • 1,190
  • 9
  • 26
  • 2
    Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Dec 29 '22 at 18:47
  • This was pretty straightforward point to error. Especially when all similar questions have already answers on it: https://stackoverflow.com/questions/47811784/passing-authorization-header-for-images-src-to-remote-server-in-ionic-page – m1ld Dec 30 '22 at 21:22
0

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

Snart
  • 54
  • 6
0

change the transform function like following:

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);
    });
}
Hassan Alhaj
  • 333
  • 3
  • 11