1 year ago
#364064
LeosSire
Angular Component/Service to return image content to URL
I am trying to setup a component/service to return base64 image content to img.src calls from html.
I have images stored on google Firebase/Firestorage which can only be accessed via method calls to get the download-url for passing to img.src.
I also have a div there I am passing html to [innerHtml]. In the html I am passing are paths to sources on my domain. The content for innterHtml is also coming from Firestorage.
I want to create a route+component to handle this. Returning the base64 to the query.
I have used toPromise to force the sequential execution and have the imgSrc variable set before ngOnInit completes.
Early completion of ngOnInit will cause a 404.
I am currently getting a 404.
Code:
Page code:
<div class="parent">
<div class="content" [innerHtml]="pageContent"></div>
<div>
content:
pageContent = "<div><h1>Hello</h1><img [src]="/path/to/images/hello.jpg"></div>
route/path in routing module:
{
path: 'path/to/images/:filename',
component: ImageComponent,
data: {
title: 'Image',
}
},
Image Component:
import { HttpClient } from "@angular/common/http";
import { Component, OnInit } from "@angular/core";
import { AngularFireStorage } from "@angular/fire/compat/storage";
import { ActivatedRoute } from "@angular/router";
import { Observable } from "rxjs";
import { ImageService } from "../../services/ApiCalls/Images/images.service";
@Component({
selector: 'image-component',
template: '{{imgSrc}}',
})
export class ImageComponent implements OnInit {
constructor(
private imageService: ImageService,
private route: ActivatedRoute,
private httpClient: HttpClient,
private firebaseStorage: AngularFireStorage,
) {
}
public imgSrc: string;
isImageLoading: boolean;
getImage(imageUrl: string): Observable<Blob> {
return this.httpClient.get(imageUrl, { responseType: 'blob' });
}
createImageFromBlob(image: Blob) {
let reader = new FileReader();
reader.addEventListener("load", () => {
return reader.result.toString();
}, false);
if (image) {
reader.readAsDataURL(image);
}
return reader.result.toString();
}
ngOnInit() {
this.route.params.toPromise().then(par => {
const filename = par['filename']
this.firebaseStorage.ref(`images/${filename}`).getDownloadURL().toPromise().then(src => {
this.getImage(src).toPromise().then(blob => {
this.imgSrc = this.createImageFromBlob(blob);
})
})
});
}
}
angular
firebase
google-cloud-firestore
angular-routing
angular-components
0 Answers
Your Answer