My approach to retrieving data from Firebase and converting it into an array of a specific type

Recently, I made the decision to expand my iOS application to also function as a web app. Although the implementation seems to be working, I am unsure if it is done correctly. I would appreciate it if someone could confirm if the implementation is correct.

Below is the function from my LicenceService:

get retriveLicences():Licence[] {

const licences: Licence[] = [];

this.afDatabase.list(this.basePath).valueChanges().subscribe((snapshot) => {
  snapshot.forEach(element => {

    const licenceObject = <any>element

    licences.push(
      new Licence(
        licenceObject.name, 
        licenceObject.logoUrl, 
        licenceObject.maxUsers, 
        licenceObject.currentUserCount, 
        licenceObject.startDate, 
        licenceObject.endDate
      )
    );
  });
});

return licences
}

Answer №1

By utilizing rxjs operators, you have the ability to "transform" the snapshot before subscribing to it:

fetchLicences(): Observable<Licence[]> {
  return this.afDatabase
  .list(`/whatever`)
  .valueChanges()
  .map(licenceObjects => {
    return licenceObjects.map(licenceObject => new Licence(
      licenceObject.name, 
      licenceObject.logoUrl, 
      licenceObject.maxUsers, 
      licenceObject.currentUserCount, 
      licenceObject.startDate, 
      licenceObject.endDate
    ));
  })
}

Alternatively, if you define an interface containing the exact variable names used in your database, Angularfire2 can simplify the process for you:

interface Licence {
  name: string;
  logoUrl: string;
  maxUsers: number;
  currentUserCount: number;
  startDate: number;
  endDate: number;
}

fetchLicences(): Observable<Licence[]> {
  return this.afDatabase.list<Licence>(`/whatever`).valueChanges();
}

Now, within your component, you can retrieve the observable from the service and easily handle it using the async pipe or any other method that suits your application better. This should streamline your development process!

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 customizing static method of a subclass from base class

Let me illustrate a simplified example of my current code: enum Type {A, B} class Base<T extends Type> { constructor(public type: T) {} static create<T extends Type>(type: T): Base<T> { return new Base(type); } } class A exte ...

Angular: a technique for creating customized error messages and modifying fields

When an error occurs in a form, the text fields are cleared and the errors are set as shown below switch(result){ case "SUCCESS": // handle success case case "ERROR1": this.Form.controls.text1.setValue(''); ...

Running two different wdio.config.js files consecutively

Is it possible to run two wdio.config.js files with different configurations, one after another? Here is how the first configuration file is defined in the code: const { join } = require('path'); require('@babel/register') exports.co ...

Guide to effectively testing a function in Angular that outputs a promise

I am trying to unit test a function inside a component that calls a service method with 3 arguments and returns a promise. I have written the necessary code in Angular using karma jasmine testing framework. Would appreciate some feedback on my implementati ...

Using Typescript to assign a custom object to any object is a powerful feature

I am attempting to organize table data by utilizing the code found at https://github.com/chuvikovd/multi-column-sort. However, I am unsure of how to pass a custom object to the SortArray[T] object. The structure of my custom object is as follows: const ob ...

In TypeScript, the error "Property does not exist on type 'any[]'" indicates that a specific property is not recognized on

Working on my project using Textscript in Next Js has been mostly smooth sailing, but I keep encountering warnings in my script that say 'Property does not exist on type any[ ]'. The red line under the name, image, and price properties is a sourc ...

How to remove a variable definition in Typescript

Is there a way to reset a variable to undefined after assigning it a value? To check, I am using the Underscore function _.isUndefined(). I have attempted both myVariable = undefined and delete myVariable without success. ...

Explanation of TypeScript typings for JavaScript libraries API

Currently, I am in the process of building an Express.js application using TypeScript. By installing @types and referring to various resources, I managed to create a functional program. However, my main query revolves around locating comprehensive document ...

When ts-loader is used to import .json files, the declaration files are outputted into a separate

I've encountered a peculiar issue with my ts-loader. When I import a *.json file from node_modules, the declaration files are being generated in a subfolder within dist/ instead of directly in the dist/ folder as expected. Here is the structure of my ...

Angula 5 presents a glitch in its functionality where the on click events fail

I have successfully replicated a screenshot in HTML/CSS. You can view the screenshot here: https://i.stack.imgur.com/9ay9W.jpg To demonstrate the functionality of the screenshot, I created a fiddle. In this fiddle, clicking on the "items waiting" text wil ...

React Typescript does not support the use of React-Router

I'm currently working on a React app that utilizes Typescript. The React version is set to "react": "^16.9.0", and the React-Router version is "react-router-dom": "^5.1.2". Within my App.tsx file, the structure looks like this: const App: React.FC ...

Tips for sending back a response after a request (post | get) is made:

In the service, there is a variable that verifies if the user is authorized: get IsAuthorized():any{ return this.apiService.SendComand("GetFirstKassir"); } The SendCommand method is used to send requests (either as a post or get request): ApiServi ...

Sign up for a service that sends out numerous simultaneous requests for every item in a list

I am encountering an issue with my Angular 5 component that is responsible for displaying a list of items. The items are fetched from a service and populated in the component by subscribing to the service. The service first makes a request to retrieve the ...

Exploring Cypress: Iterating over a collection of elements

I have a small code snippet that retrieves an array of checkboxes or checkbox labels using cy.get in my Angular application. When looping through the array to click on each element and check the checkboxes, it works fine if the array contains only one elem ...

Angular App Failing to Validate Session Cookie 'sessionId' in AuthGuard

Encountering a perplexing issue with my Angular application where the AuthGuard fails to recognize a session cookie named 'sessionId' correctly. I have successfully implemented user authentication, and the expected behavior is for users to be dir ...

Asynchronous jQuery operations using promises and finally functionality

I am attempting to interact with a REST api using jQuery's ajax feature. My goal is to return the Promise<Customer> object, but I am encountering an error stating that the property finally is missing. It used to work before, so I assume there h ...

Struggling to apply custom styles to ng-content? Find out why the ::ng-deep selector

Attempting to customize the appearance of elements inside <ng-content> within anuglar2 <au-fa-input > <input type="text" class="form-control" placeholder="email" #input> </au-fa-input> In the CSS of the au-fa-input component, ...

Troubleshooting Problem with Angular 2 Jquery Plugin Upon Returning to Page

I am utilizing the Seriously plugin to present HTML videos on a canvas element. Everything works perfectly during the initial visit to the page, but upon returning, all the videos vanish without any console errors. import {Component, ViewChi ...

Dynamic Object properties are not included in type inference for Object.fromEntries()

Hey there, I've been experimenting with dynamically generating styles using material UI's makeStyles(). However, I've run into an issue where the type isn't being correctly inferred when I use Object.fromEntries. import * as React from ...

solution for downloading large files from authenticated endpoint that works across multiple web browsers

I'm currently on the lookout for a solution to download large files (around 2 - 4 GB) from a bearer token protected api endpoint that is compatible with all common browsers including IE 11, Chrome, Firefox, Android Browsers, and Safari. I want it to w ...