The type 'FileUpload[][]' cannot be assigned to the type 'AngularFireList<FileUpload[]>'

I'm currently working on an Angular application integrated with Firebase for the purpose of uploading images to the database and retrieving them as well.

upload-file.service.ts

import {Injectable} from '@angular/core';
import {AngularFireDatabase, AngularFireList} from 'angularfire2/database';
import * as firebase from 'firebase';

import {FileUpload} from '../uploadingpage/fileupload';

@Injectable()
export class UploadFileService {

  constructor(private db: AngularFireDatabase) {}
  getFileUploads (): AngularFireList<FileUpload[]>{
        return this.db.list('/uploads');
    }

  private basePath = '/uploads';
  fileUploads: AngularFireList<FileUpload[]>;

  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);
  }
}

uploadingpage.component.ts

import { Component, OnInit } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
import { AngularFireDatabase, AngularFireObject } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';
import * as firebase from 'firebase';
import { FirebaseAuthService } from '../auth/firebase-auth.service';

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

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

  //for image
  selectedFiles: FileList;
  currentFileUpload: FileUpload;
  progress: {percentage: number} = {percentage: 0};


  constructor(
    private afDb: AngularFireDatabase,
    private _auth: FirebaseAuthService,
    private itemService: ItemService,
    private uploadService: UploadFileService 
  ) { }

  ngOnInit() {
  }

  //for image
  selectFile(event) {
    this.selectedFiles = event.target.files;
  }
 //for image
  upload() {
    const file = this.selectedFiles.item(0)
    this.currentFileUpload = new FileUpload(file);
    this.uploadService.pushFileToStorage(this.currentFileUpload, this.progress);
  }

  signOut(){
    this._auth.signOut();
    window.location.href = "";    
  }
}

displaypage.component.ts

import { Component, OnInit } from '@angular/core';
      //additional imports
      import { ItemService } from '../services/item.service';
      import {FileUpload} from '../uploadingpage/fileupload';
      import {UploadFileService} from '../services/upload-file.service';
      import { AngularFireDatabase, AngularFireList } from 'angularfire2/database'; 
      import * as firebase from 'firebase';

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

        fileUploads: AngularFireList<FileUpload[]>;

        constructor(private itemService: ItemService, private uploadService: UploadFileService) { }

        ngOnInit() {
          this.itemService.getItems().subscribe(items => {
            this.items = items;
          });
         this.uploadService.getFileUploads().valueChanges().subscribe(result=>{
             this.fileUploads = result;
         });
        }

      }

Although I have successfully implemented image upload and retrieval functionalities using Firebase, I encountered an error displayed in my terminal stating:

Type 'FileUpload[][]' is not assignable to type 'AngularFireList<FileUpload[]>
Property 'query' is missing in type 'FileUpload[][]'.

If anyone could provide insights into why this error is occurring, it would be highly appreciated. Thank you for your assistance.

Answer №1

Avoid using the AngularFireList type in this scenario,

Instead, create a class like so:

export class Upload {

  $key: string;
  name: string;
  url: string;
  file: File;
  progress:number;
  timestamp: Date = new Date();

  constructor(file: File) {
    this.file = file;
  }
}

In your service implementation, do the following:

uploads: Observable<Upload[]>;

getUploads() {
  this.uploads = this.db.list(this.basePath).snapshotChanges().map((actions) => {
    return actions.map((a) => {
      const data = a.payload.val();
      const $key = a.payload.key;
      return { $key, ...data };
    });
  });
  return this.uploads;
}

And within your component code:

uploads: Observable<Upload[]>;
ngOnInit() {
  this.uploads = this.uploadService.getUploads();   
}

To display the results on your page, modify the HTML as follows:

<div *ngIf="uploads | async; let uploads; else loading"> 
<div *ngFor="let upload of uploads"> 
<img [src]="file.url" id="image" /> 
</div> 
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Step-by-step guide to integrating Google AdSense ads.txt file into an Angular project

If you're experiencing problems with Google AdSense in your Angular project, it could be related to how static files are served within Angular and handled by servers. Let's go through the necessary steps to ensure that your ads.txt file is proper ...

React Scheduler by Bryntum

After successfully discovering some functions related to various actions, I find myself still in need of additional functions: Currently, I am utilizing these functions by passing them directly as props to the Scheduler React Component: - onBeforeEventSa ...

Capacitor and Angular: Trouble with appStateChange listener functionality

In my quest to solve a KPI, I am attempting to trigger a logEvent using the Firebase SDK when the user closes the application (specifically in an Ionic/Capacitor/Angular environment). However, I am facing numerous challenges trying to access the appStateCh ...

Attempting to create a login feature using phpMyAdmin in Ionic framework

Currently, I am in the process of developing a login feature for my mobile application using Ionic. I am facing some difficulties with sending data from Ionic to PHP and I can't seem to figure out what the issue is. This is how the HTML form looks li ...

Tips for stopping TypeScript code blocks from being compiled by the Angular AOT Webpack plugin

Is there a way to exclude specific code from Angular's AOT compiler? For instance, the webpack-strip-block loader can be utilized to eliminate code between comments during production. export class SomeComponent implements OnInit { ngOnInit() { ...

Discovering the best way to utilize pagination for searching all data within Angular 8

Hey there, good morning everyone! I'm currently working on an Angular 8 app that showcases a table filled with data from a database. This table comes equipped with a search box and a pagination feature using the "Ng2SearchPipeModule" and "JwPaginatio ...

The console is displaying an undefined error for _co.photo, but the code is functioning properly without any issues

I am facing an issue with an Angular component. When I create my component with a selector, it functions as expected: it executes the httpget and renders a photo with a title. However, I am receiving two errors in the console: ERROR TypeError: "_co.photo ...

Transferring information between components, specifically when one of them is a routerOutlet within an Angular application

I need to transfer data from the category component to the product component within the dashboard component. However, I am facing an issue due to the presence of a router outlet inside the product component. View Dashboard Screen dashboard.component.html ...

The correct way to incorporate a global property into a component template (using Vue 3, Vite, TypeScript, and the Composition API)

The component's property is not functioning properly https://i.sstatic.net/qaUG9.png src/main.ts import { createApp } from 'vue' import languagePlugin from '@/plugins/languagePlugin' import App from './App.vue' const a ...

Using ngModel in multiple mat-select elements in Angular 2/4

I have a mat-select dropdown list that allows multiple selections and I am using NgModel to keep track of the user's selected values. The issue arises when I navigate away from the page and return, the user's selected values are not preserved in ...

Position filter forms on the left side to align with bootstrap cards

I'm having trouble aligning the cards using Bootstrap's row and col- classes. The first three are behaving as expected, but the fourth one isn't cooperating. Any idea why this might be happening and any solutions you can suggest? View the i ...

Exporting declarations and different export types within a TypeScript ambient module

I am currently working on adding specific types for the config module in our application. The config module is generated dynamically from a JSON file, making it challenging to type. Since it is a node module, I am utilizing an ambient module for the typing ...

A programming element that is capable of accessing a data member, but mandates the use of a setter method for modifications

I am unsure whether I need a class or an interface, but my goal is to create an object with a member variable that can be easily accessed like a regular variable. For example: interface LineRange { begin: number; end: number; } However, I want th ...

implement some level of control within the ngFor directive in Angular

For instance, let's say I have an ngfor loop: <ng-container *ngFor="let setting of settings | trackBy: trackById"> <button mat-button [matMenuTriggerFor]="menu">Menu</button> <mat-me ...

Trying to automatically select a checkbox upon page load in Angular 6

When the page loads, I want to automatically check a checkbox. Here is my component: var user = ViewprojectComponent.featuresList1; this.rules_id = user[0]; for(let i = 0; i <= this.rules_id.length; i++) { var checkedOn1 = this.rules_id[i]; this.Ru ...

Steps for running an Angular application in IntelliJ:1. Open IntelliJ IDEA

I'm currently navigating through IntelliJ to set up Angular support. https://www.jetbrains.com/help/idea/2017.1/using-angular.html#install_angular_cli After successfully creating the project, I am unsure of how to run it. My guess is that I need to ...

An error occurred due to an unexpected token found in the JsonForms custom-renderer props

I found inspiration in an example from this website to develop a custom renderer for JsonForms using Vue: However, as I implement this example in my .vue file within the script tags, I encounter an error UnexpectedToken right after declaring the props. It ...

Passing parameters to an Angular 2 component

When it comes to passing a string parameter to my component, I need the flexibility to adjust the parameters of services based on the passed value. Here's how I handle it: In my index.html, I simply call my component and pass the required parameter. ...

Encountering a d3.js runtime issue following the transition to Angular 8

I've been experimenting with upgrading my Angular 6 application to Angular 8. It compiles fine, but I'm facing a runtime error as soon as it runs: "d3.js:8 Uncaught TypeError: Cannot read property 'document' of undefined". The specific ...

Tips for ensuring proper dependency regulations in javascript/typescript/webpack

In essence, I am in search of a method to limit dependencies, similar to how one would manage different projects (libraries) in Java or C#. Think of it as friend or internal access modifiers. I'm considering various approaches to accomplish this (suc ...