Ad

Getting Download URL And Make It Available To Other Components

I'm new developer using Angular and Firebase Storage. I have successfully uploaded documents in the Firebase Storage but i's stuck on how i can fetch the download URL and make it available to other components.

I have tried using then after finalize() to have it added but was giving me some new problems

import { Component, OnInit } from '@angular/core';
import {AngularFireUploadTask, AngularFireStorage} from '@angular/fire/storage';
import { AngularFirestore } from '@angular/fire/firestore';
import { Observable } from 'rxjs';
import { tap, finalize } from 'rxjs/operators';

@Component({
  selector: 'app-upload-page',
  templateUrl: './upload-page.component.html',
  styleUrls: ['./upload-page.component.css']
})
export class UploadPageComponent implements OnInit {

 task: AngularFireUploadTask;

  // Progress monitoring
  percentage: Observable<number>;

  snapshot: Observable<any>;

  // Download URL
  downloadURL: Observable<string>;

  // State for dropzone CSS toggling
  isHovering: boolean;

  constructor(
    private storage: AngularFireStorage,
    private db: AngularFirestore
  ) {}

  toggleHover(event: boolean) {
    this.isHovering = event;

  }

  startUpload(event: FileList) {
    // The File object
    const file = event.item(0);

    // The storage path
    const path = `documents/${new Date().getTime()}_${file.name}`;

    // metadata
    const customMetadata = { app: 'LKMData in '+ file.type+ ' Format' };

    // The main task
    this.task = this.storage.upload(path, file, { customMetadata });

    // Progress monitoring
    this.percentage = this.task.percentageChanges();
    this.snapshot = this.task.snapshotChanges().pipe(
      tap(snap => {
        if (snap.bytesTransferred === snap.totalBytes) {
          // Update firestore on completion
          this.db.collection('documents').add({ path, size: snap.totalBytes});
        }
      }),
       finalize(() => this.downloadURL = this.storage.ref(path).getDownloadURL())
    );

  }

  // Determines if the upload task is active
  isActive(snapshot) {
    return (
      snapshot.state === 'running' &&
      snapshot.bytesTransferred < snapshot.totalBytes
    );
  }

  ngOnInit() {
  }

}

I expecting to have the download URL be send to the Firebase database and update the details holding the file uploaded or have a way to make all the URLS of files in the storage available for use in the components

Ad

Answer

The StorageReference.getDownloadURL() method is asynchronous. Only once the call completes is the download URL available.

So:

this.storage.ref(path).getDownloadURL().then((url) => {
  this.downloadURL = url;
});

Also see:

Ad
source: stackoverflow.com
Ad