Trouble accessing images from database in Angular 2 with Firebase

Recently, I've integrated an image upload feature for my database using the following function:

  private saveFileData(upload: Upload): void {
    this.firebaseAuth.authState.subscribe(auth => {
    this.db.list(`uploads/${auth && auth.email && auth.uid}`).push(upload);
    })
  }

Now, I'm trying to retrieve the uploaded images by logged-in users only. For this purpose, a pathreference is crucial as it ensures that each user sees only their uploads:

this.firebaseAuth.authState.subscribe(auth => {
  if(auth && auth.email && auth.uid) {
this.uploadRef = this.db.list<any>(`uploads/${auth && auth.email && auth.uid}`);
    console.log("Retrieving profile data")
  }
  else {
    console.log("Image not found")
  }

})

Furthermore, I want to display a list of all the uploaded images in a similar manner:

get getListUploads(): Observable<AngularFireAction<DatabaseSnapshot>[]> {
    return this.uploadRef.snapshotChanges().map(changes => {
      return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
    });
  }

However, an error arises in the console:

ERROR TypeError: Cannot read property 'snapshotChanges' of undefined
    at UploadService.get [as getListUploads] (upload.service.ts:30)

Although the upload process functions correctly and images are successfully stored in the database, I encounter difficulties retrieving them. Any suggestions on how to resolve this issue?

Answer №1

Your file reference is incorrect because you are using conditions to save it:

auth && auth.email && auth.uid

Check what it returns when used in JavaScript:

console.log({auth: true} && '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c4a2ababeaa6a5b684a3a9a5ada8eaa7aba9">[email protected]</a>' && 207894193784);

This means that only the ID is used in the name when saving your post.

Now let's test without one of the conditions being fulfilled:

console.log({auth: true} && '' && 207894193784);

As seen, if the email is not provided, no name is displayed.

You should update your file reference to resolve this issue on its own.

EDIT A service example is provided below:

import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { AngularFireStorage } from 'angularfire2/storage';

@Injectable()
export class StorageService {

  constructor(
    private afsStorage: AngularFireStorage
  ) { }

  createFile(file: File, folder = 'unclassified'): Observable<string> {
    const path = `${Date.now()}-${Math.random().toString(36).slice(-8)}.${file.name.split('.').splice(-1)}`;
    return this.afsStorage.upload(`${folder}/${path.toLowerCase()}`, file).downloadURL();
  }

  removeFile(url: string): Observable<any> {
    const ref = this.afsStorage.storage.refFromURL(url);
    return Observable.fromPromise(ref.delete());
  }
}

The first method allows you to create a file and returns a URL. Once you have the URL, you can store it in your database as a document.

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

Issue encountered in app.module.ts while attempting to incorporate AngularMultiSelectModule

Currently, I am utilizing angular version 6 and attempting to incorporate the angular2-multiselect-dropdown in my application. Upon launching the app and following the steps outlined in this guide: and also here: https://www.npmjs.com/package/angular2-mul ...

What is the best way to integrate Tawk.to into a React application while using typescript?

Having some issues integrating tawk.to into my website built with React and TypeScript. I have installed their official npm package, but encountered an error message: import TawkMessengerReact from '@tawk.to/tawk-messenger-react'; Could not fin ...

Guide to implement editable columns in Angular 4 with a click functionality

I have a table displaying records using ngFor, and I am looking to enable editing of a column upon clicking it. <tr *ngFor="let cd of descriptionCodes; let i = index"> <td><input type="checkbox"></td> <td> {{cd.code}} ...

Which library do you typically employ for converting .mov files to mp4 format within a React application using Typescript?

As a web programming student, I have encountered a question during my project work. In our current project, users have the ability to upload images and videos. Interestingly, while videos can be uploaded successfully on Android devices, they seem to face ...

Issues with the 'GET' request functionality on the deployed Angular project

I am attempting to run an Angular project that I have built. After copying the folder generated from 'ng build' and placing it in the directory where my back end code (using express) is located, I am trying to run it on my laptop at port 3000. Wh ...

Having trouble clicking on a button with Protractor because the button text is located within a child span element

Having trouble clicking a button with protractor. The DOM structure is displayed in the image above. Here are some of the locators I've attempted to use: element(by.xpath("(//div[@class='mat-drawer-backdrop ng-star-inserted'])//a followin ...

The CSS formatting is not being properly applied within the innerHTML

I have a scenario where I am trying to display a Bootstrap card using innerHTML in my TS file, but the styles are not being applied to this content. I suspect that the issue might be because the styles are loaded before the component displays the card, cau ...

Storing information upon refresh in Angular 8

When it comes to inter-component communication in my Angular project, I am utilizing BehaviourSubject from RXJS. Currently, I have a setup with 3 components: Inquiry Form Where users enter an ID number to check for summon-related information. This data ...

Facing problem with implementing NgMoudleFactoryLoader for lazy loading in Angular 8

A situation arose where I needed to lazy load a popups module outside of the regular router lazy-loading. In order to achieve this, I made the following adjustments: angular.json "architect": { "build": { ... "options": { ... "lazyM ...

Utilizing custom routing rules to fetch data from a local JSON file using http.get in Angular 2

Currently facing a challenge with Angular as a beginner, specifically when attempting to retrieve a local .json file using http.get. The issue seems to be related to my routing configuration, and I'm unsure how to resolve it. File Structure: api ...

Collaborate on code for a cross-platform mobile application and a traditional desktop web application

I have a vision to create a cutting-edge app that can be utilized as both a hybrid mobile application and a desktop web application. For the most part, the logic and user interface will remain consistent across both versions. However, there are a few key ...

Optimizing Angular Performance with Trackby in Dual Lists

How can I write two ngFor lists with trackby to prevent elements from being recreated when moving between the lists? I know that trackby helps in avoiding recreation of elements within a single list, but is there a way to achieve this across multiple list ...

Tips for retrieving the generated ID from the server immediately following form submission using the Post method in TypeScript

When submitting a long-form, it is important to ensure that no data is lost. Users should be able to stay on the same page to make any necessary changes after clicking the submit button. I need to receive the unique id generated by the server upon submissi ...

The Angular component fails to display the rendered HTML and instead displays the route for the HTML

I just finished creating a new Angular component, but when I try to view the rendered HTML, all I see is the route to the HTML file instead of the actual content. Here is my folder structure: This is the component I created, named server.component.ts: i ...

Issue with form array patching causing value not to be set on material multiple select

When attempting to populate a mat-select with multiple options using an array of ids from Firestore, I encountered an issue. The approach involved looping through the array, creating a new form control for each id, and then adding it to the formArray using ...

The TS2583 error in TypeScript occurs when it cannot locate the name 'Set' within the code

Just started my Typescript journey today and encountered 11 errors when running tsc app.ts. Decided to tackle them one by one, starting with the first. I tried updating tsconfig.json but it seems like the issue lies within node_modules directory. Any help ...

What is the best way to have Vue i18n fetch translations from a .json file during Unit Testing?

Previously, with vue-i18n (v8.25.0 and vue v2.6.14), I stored all translations in .ts files containing JS objects: import { LocaleMessages } from 'vue-i18n' const translations: LocaleMessages = { en: { test: 'Test', }, } expor ...

Key factors to keep in mind when comparing JavaScript dates: months

Check the dates and determine if the enddate refers to the following month by returning a boolean value. Example startdate = January 15, 2020 enddate = February 02, 2020 Output : enddate is a future month startdate = January 15, 2020 enddate = January 2 ...

I'm encountering an issue where Typescript is unable to locate the Firebase package that I

I have a TypeScript project that consists of multiple .ts files which need to be compiled into .js files for use in other projects. One of the files requires the firebase package but it's not being found. The package is installed and located inside t ...

SonarQube flagging a suggestion to "eliminate this unnecessary assignment to a local variable"

Why am I encountering an error with SonarQube? How can I resolve it since the rule page does not offer a specific solution? The suggestion is to eliminate the unnecessary assignment to the local variable "validateAddressRequest". validateAddress() { ...