[Fixed] Is there a simple way to get the download url from firesbase-storage paths in Angular templates

Issue

I have seen examples where people have saved the actual download path into firestore, then later use that image image in the templates.

However i am not so sure that is the correct method to save locations of files. For the simple reason when retrieving the download url it contains tokens, which I assumes is for the current user getting the download url.

So what I have been doing on every template I have received I would have to get the downloadUrl with the components code for the download url. Is there a way to avoid this a just have it directly in the templates files. So I do not need to manipulate simple display data, that contains image refs to firestorage.

Solution

You can create a simple pipe for this:

import { Pipe, PipeTransform } from '@angular/core';
import { AngularFireStorage } from '@angular/fire/storage';
import { Observable, from } from 'rxjs';

@Pipe({
   name: 'firestoagePath'
})
export class FirestoagePathPipe implements PipeTransform {
    constructor(private storage: AngularFireStorage) { }
    transform(value: string, ...args: unknown[]): Observable<string> {
      if (typeof (value) === 'string') {
          const storageRef = this.storage.ref(value);
          return storageRef.getDownloadURL();
      }
      return from(value);
   }
}

With pipes you can do injections to the firestore which is nice, get the download url and chain it with async pipe like so:

<img *ngIf="firestoreObject.image.croppedSource | firestoagePath | async as imageSource"
    [src]="imageSource">

in this example the firestoreObject is a random object, with a image that has a string path to the location of cropped image file on firestorage.

Leave a Reply

(*) Required, Your email will not be published