Angular 4 Firebase – Get List Files from Storage

In previous post, we have known how to upload file to Firebase Storage. This tutorial shows you way to get List Files and display in a simple Angular 4 App.

Updated Post:
Angular 5 Firebase – Upload/Display/Delete Files from Storage

Related Posts:
How to integrate Firebase with Angular 4
Angular 4 Firebase – Upload File to Storage
Angular 4 Firebase – Delete File from Storage

I. Technology

– Angular 4
– AngularFire2 4.0

II. How to do

1. Set up the Firebase Project & integrate Firebase with Angular 4 App

Please visit this post to know step by step.

2. Upload File Service

We get List Files from Firebase Storage by files’info (name/url) stored in Firebase Realtime Database.

import {AngularFireDatabase, FirebaseListObservable} from 'angularfire2/database';

@Injectable()
export class UploadFileService {

  private basePath = '/uploads';
  fileUploads: FirebaseListObservable;

  constructor(private db: AngularFireDatabase) {}
  // ...
  getFileUploads(query = {}) {
    this.fileUploads = this.db.list(this.basePath, {
      query: query
    });
    return this.fileUploads
  }
}

To know how to save file info to Firebase Realtime Database, please visit previous post:
Angular 4 Firebase – Upload File to Storage

3. Get and display List of Files
import {FirebaseListObservable} from 'angularfire2/database';
import {FileUpload} from '../fileupload';
import {UploadFileService} from '../upload-file.service';

export class ListUploadComponent implements OnInit {

  fileUploads: FirebaseListObservable;

  ngOnInit() {
    this.fileUploads = this.uploadService.getFileUploads({limitToLast: 6})
  }
}

HTML template:


III. Practice

1. Project Overview
1.1 Goal

We will build an Angular 4 Firebase App that can:
– helps user choose file from local and upload it to Firebase Storage
– show progress with percentage
– save metadata to Firebase Realtime Database
(previous post‘s functions above)
– display list files from Firebase Storage

angular-4-firebase-storage-get-list-files-overview

1.2 Structure

angular-4-firebase-storage-get-list-files-structure

2. Step by step
2.1 Set up the Firebase Project & integrate Firebase with Angular 4 App

Please visit this post to know step by step.

angular-4-firebase-integration-copy-firebase-project-config

2.2 Add Firebase config to environments variable

Open /src/environments/environment.ts, add your Firebase configuration that we have saved when Popup window was shown:

export const environment = {
  production: false,
  firebase: {
    apiKey: 'xxx',
    authDomain: 'javasampleapproach-angular4.firebaseapp.com',
    databaseURL: 'https://javasampleapproach-angular4.firebaseio.com',
    projectId: 'javasampleapproach-angular4',
    storageBucket: 'javasampleapproach-angular4.appspot.com',
    messagingSenderId: 'xxx'
  }
};
2.3 Setup @NgModule
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';

import {AngularFireDatabaseModule} from 'angularfire2/database';
import {AngularFireModule} from 'angularfire2';

import {AppComponent} from './app.component';
import {FormUploadComponent} from './upload/form-upload/form-upload.component';
import {UploadFileService} from './upload/upload-file.service';

import {environment} from '../environments/environment';

@NgModule({
  declarations: [
    AppComponent,
    FormUploadComponent
  ],
  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireDatabaseModule
  ],
  providers: [UploadFileService],
  bootstrap: [AppComponent]
})
export class AppModule {}
2.4 Model Class
export class FileUpload {

  $key: string;
  name: string;
  url: string;
  file: File;

  constructor(file: File) {
    this.file = file;
  }
}
2.5 Service
import {Injectable} from '@angular/core';
import {AngularFireDatabase, FirebaseListObservable} from 'angularfire2/database';
import * as firebase from 'firebase';

import {FileUpload} from './fileupload';

@Injectable()
export class UploadFileService {

  private basePath = '/uploads';
  fileUploads: FirebaseListObservable;

  constructor(private db: AngularFireDatabase) {}

  pushFileToStorage(fileUpload: FileUpload, progress: {percentage: number}) {
    const storageRef = firebase.storage().ref();
    const uploadTask = storageRef.child(`${this.basePath}/${fileUpload.file.name}`).put(fileUpload.file);

    uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
      (snapshot) => {
        // in progress
        const snap = snapshot as firebase.storage.UploadTaskSnapshot
        progress.percentage = Math.round((snap.bytesTransferred / snap.totalBytes) * 100)
      },
      (error) => {
        // fail
        console.log(error)
      },
      () => {
        // success
        fileUpload.url = uploadTask.snapshot.downloadURL
        fileUpload.name = fileUpload.file.name
        this.saveFileData(fileUpload)
      }
    );
  }

  private saveFileData(fileUpload: FileUpload) {
    this.db.list(`${this.basePath}/`).push(fileUpload);
  }

  getFileUploads(query = {}) {
    this.fileUploads = this.db.list(this.basePath, {
      query: query
    });
    return this.fileUploads
  }
}
2.6 Form Upload Compoment
import {Component, OnInit} from '@angular/core';

import {UploadFileService} from '../upload-file.service';
import {FileUpload} from '../fileupload';

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

  selectedFiles: FileList
  currentFileUpload: FileUpload
  progress: {percentage: number} = {percentage: 0}

  constructor(private uploadService: UploadFileService) {}

  ngOnInit() {
  }

  selectFile(event) {
    this.selectedFiles = event.target.files;
  }

  upload() {
    const file = this.selectedFiles.item(0)
    this.currentFileUpload = new FileUpload(file);
    this.uploadService.pushFileToStorage(this.currentFileUpload, this.progress)
  }
}

form-upload.component.html:

{{progress.percentage}}%
2.7 DetailsUpload Component

details-upload.component.ts

import {Component, OnInit, Input} from '@angular/core';
import {FileUpload} from '../fileupload';

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

  @Input() fileUpload: FileUpload;

  constructor() {}

  ngOnInit() {
  }
}

details-upload.component.html

{{fileUpload.name}}
2.8 ListUpload Component

list-upload.component.ts

import {Component, OnInit} from '@angular/core';

import {FirebaseListObservable} from 'angularfire2/database';
import {FileUpload} from '../fileupload';
import {UploadFileService} from '../upload-file.service';

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

  fileUploads: FirebaseListObservable;

  constructor(private uploadService: UploadFileService) {}

  ngOnInit() {
    this.fileUploads = this.uploadService.getFileUploads({limitToLast: 6})
  }

}

list-upload.component.html

List of Files
2.9 App Component

app.component.ts

import {Component} from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'JavaSampleApproach';
  description = 'Angular4-Firebase Demo';
}

app.component.html

{{title}}

{{description}}



2.10 Check Result

Run the App, go to http://localhost:4200/.

angular-4-firebase-storage-get-list-files-overview

Upload new file:
angular-4-firebase-storage-get-list-files-result

IV. Source Code

Angular4FirebaseStorage-GetListFiles

4 thoughts on “Angular 4 Firebase – Get List Files from Storage”

  1. ERROR in src/app/list-upload/list-upload.component.ts(3,9): error TS2305: Module ‘”/home/pedro/Projects/VenztecMaps/node_modules/angularfire2/database/index”‘ has no exported member ‘FirebaseListObservable’.
    src/app/services/uploadfile.service.ts(13,16): error TS2304: Cannot find name ‘FirebaseListObservable’.
    src/app/services/uploadfile.service.ts(44,7): error TS2345: Argument of type ‘{ query: {}; }’ is not assignable to parameter of type ‘QueryFn’.
    Object literal may only specify known properties, and ‘query’ does not exist in type ‘QueryFn’.

    I have this error in console :c

    1. Hi VengadorWeb,

      This tutorial uses AngularFire2 V4.
      FirebaseListObservable is replaced by AngularFireList in AngularFire2 V5. We will post new tutorials for AngularFire2 V5 in the future.

      Regards,
      JSA.

  2. ERROR in src/app/upload/upload-file.service.ts(46,7): error TS2345: Argument of type ‘{ query: {}; }’ is not assignable to parameter of type ‘QueryFn’.
    Object literal may only specify known properties, and ‘query’ does not exist in type ‘QueryFn’.

    1. Hi minakshi,

      This tutorial uses AngularFire2 V4. We will post new tutorials for AngularFire2 V5 in the future.

      Regards,
      JSA.

Leave a Reply

Your email address will not be published. Required fields are marked *