I'm loading products from server to Angular.And the imagepaths/images are attached with the products.The images are present at server port localhost:3000
.And the path for images is ./assets/imagename
.But the images are not visible and the console shows me the following error
Custom Pipe for safe url and Domsanitizer
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({
name: 'safeurl',
})
export class SafeurlPipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {}
transform(html: any) {
return this.sanitizer.bypassSecurityTrustResourceUrl(html);
}
ngOnInit Getting all the products from server
results?: Book[];
ngOnInit() {
this.apiService.getallbooks().subscribe((data: Book[]) => {
this.results = data;
console.log(this.results);
});
}
html code.I tried with both data:image/jpg;base64
and data:image/png;base64
but the results are same
<div *ngFor="let result of results">
<div style="padding: 0.5rem; z-index: 100">
<div *ngIf="image">
<img
[src]="'data:image/png;base64,' 'http://localhost:3000/' result.coverimage | safeurl"
alt=""
height="400px"
width="250px"
style="border: 1px solid red"
/>
</div>
The error still remain even if I don't use http://localhost:3000/
in src
CodePudding user response:
It seems to me that your URL is not correct. You currently have:
data:image/png;base64.http://localhost etc...
This is not a valid http format.
Can you verify this theory by hard-coding a test URL in the source?
If it works it will allow us to validate that it is just a question of writing the URL.
CodePudding user response:
You can try to use pipe in component.ts
.component.ts
constructor(...
private safeurlPipe: SafeurlPipe) {
}
genImageUrl(coverimage: any): SafeResourceUrl {
const safeResourceUrl = this.safeurlPipe.transform('data:image/png;base64,http://localhost:3000/' coverimage);
return safeResourceUrl;
}
.component.html
<div *ngFor="let result of results">
<div style="padding: 0.5rem; z-index: 100">
<div *ngIf="image">
<img
[src]="genImageUrl(result.coverimage)"
alt=""
height="400px"
width="250px"
style="border: 1px solid red"
/>
</div>
</div>
</div>