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