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

Exploring the Angular Heroes Journey: What's the significance of one being labeled with a colon while the other is identified

Setting: Angular 5+ Source: https://angular.io/tutorial Within the heroes.component.ts class, we see an assignment using a colon: export class HeroesComponent implements OnInit { heroes: Hero[]; However, in the app.component.ts class, a different as ...

Getting a JSON value and saving it to a variable in Angular 4

Here is the JSON structure: { "Semester": [ { "queueName": "Science", "totalCount": 300, "unassignedCount": 10, "subjectDetails": [ { "subjectName": "Chemistry", "sectionOne": 100, "secti ...

Mastering the incorporation of Context in React with Typescript

I am currently in the process of setting up a context provider for my Next.js application using TypeScript. Although I have previously set up a context provider in React using plain JavaScript, this time I am delving into learning TypeScript. In the code ...

Having trouble with the download link for files in Angular?

I am facing an issue with a PDF file in my Angular website application. The file is 33 KB and located at src/app/components/landing-page/res/File.pdf In the landing-page.component.html within the landing-page folder, I added the following line to enable ...

Angular 14 presents an issue where the injectable 'PlatformLocation' requires compilation with the JIT compiler; however, the '@angular/compiler' module is currently missing

I've encountered the following error and have tried multiple solutions, but none of them have been successful: Error: The injectable 'PlatformLocation' requires JIT compilation with '@angular/compiler', which is not available. ...

In the process of developing a custom Vue component library with the help of Rollup and VueJS 3

My goal is to develop a custom Vue component library using rollup and Vue.js. The process went smoothly with Vue2, but I encountered issues parsing CSS files with Vue3. To address this, I updated the dependencies in the package.json file. package.json { ...

Encountered an error while attempting to load http://localhost:9999/auth-service/oauth/token: The response for preflight request returned an unexpected HTTP status code

When attempting to generate an OAuth2 token, I utilized Spring Boot OAuth2 and Angular 5. In Postman and curl, I successfully generated the token by providing the appropriate values. However, when using the same parameters in the Angular POST request, it ...

"Troubleshoot: Main child route in Angular 2 not functioning correctly

Below is the configuration of the child routes for my project: export const ProjectRouter: RouterConfig = [ { path: 'projects', component: MainProjectComponent, children: [ { path: 'new', component: NewProjectComponent, can ...

Crystal-clear TextField component in Office UI Fabric

Seeking advice on how to clear a masked text field from Office UI Fabric using a button. Does anyone have a solution for this? I attempted to set the value using a state, but unfortunately, it did not work as expected. ...

Unlinked Typescript blob file name

Is there a way to set the file name for a blob in typescript? I have found a solution for IE, but it seems impossible for Chrome. I need something similar to this solution, but in typescript. downloadFile(data: any) { var blob = new Blob([data], {type ...

Angular's GET HTTP request has resulted in a 500 error message, specifically the Internal Server Error

Attempting to send a GET request to the server where only authenticated users can access a specific route ("/user") after logging in. However, even after a successful login, users are unable to gain access to the "/user" route. A middleware function named ...

Edge browser saves your most recent PDF viewing preferences

Within my Angular application, we have integrated a feature where users can view a PDF report downloaded via an API within an iFrame. .TS code: In the TypeScript code snippet provided, we are subscribing to the execution of the reportservice and handling ...

Incorporate Ng-Survey multiple times within one component

Incorporating the ng-surveys template into my Angular application via has been successful. However, I encountered an issue where when using the template selector *ngFor to display multiple surveys on the same page, the browser treats all the surveys as id ...

Files for the Express API and Sequelize are nowhere to be found

After collaborating with a Freelance developer for more than 10 months on a project, the developer suddenly disappeared without warning. Although he sent me a file containing the work he had completed, I realized that the backend API was missing. Project ...

Using Angular2's *ngIf directive to conditionally display content based on the length of

After referring to https://angular.io/docs/ts/latest/guide/displaying-data.html and a stack post on how to check for an empty object in an angular 2 template using *ngIf, I am still encountering a syntax error stating "self context undefined". If I remove ...

Discovering the quantity of items with a specific value in Angular 8

I'm attempting to determine the number of objects with a status value of 'Served', which should yield 2. I'm unsure about the method I should use to achieve this. Any suggestions on which method would be best? {full_name: 'Jenny&a ...

While trying to set up a development server in Firebase, I mistakenly deleted my build folder

I recently encountered an issue with my Firebase project. While trying to set up a development server for my existing React web app that is already in production, I ran into some unexpected problems. firebase use bizzy-book-dev firebase init firebase ...

Trouble Integrating svgr/webpack with Webpack 5 and SingleSpa

I've been grappling with this issue for the past week. Despite scouring through numerous Stack Overflow threads and reading the SVGR/WEBPACK documentation, I haven't been able to find a solution. I decided to upgrade an old React single-spa appl ...

waiting for the import statement in a React/NextJS/Typescript project to resolve

While working on my node.js development server, I encountered a problem with the following code: import { useRouter } from 'next/router' import nextBase64 from 'next-base64'; const Load = () => { const router = useRouter() co ...

In Angular components, data cannot be updated without refreshing the page when using setInterval()

Here's the Angular component I'm working with: export class UserListComponent implements OnInit, OnDestroy { private _subscriptions: Subscription; private _users: User[] = []; private _clickableUser: boolean = true; constructor( priv ...