Processing a list in Angular using Observables

In my Angular12 application, I am fetching data from a Firebase Realtime DB using AngularFire. To streamline my code and ensure consistency, I have implemented a DAO service to preprocess the retrieved data (e.g., converting string dates to Date objects). However, this preprocessing step has caused me to lose the subscription functionality, compromising the real-time data benefits of my app. I am now exploring options to return an Observable list after performing the preprocessing.

Current implementation:

FantaroiDAOService

  private list = this.db.list<Fantaros>('fantaroi')

  constructor(private db: AngularFireDatabase){}

  public getIpir() {
    return this.list.valueChanges();
  }

AppComponent

  ngOnInit(): void {
    let fantaroi: Fantaros[] = [];
    this.dao.getIpir().subscribe(f => {
      fantaroi = f.map(f => {
        const soc = f.soc.map(date => new Date(date))
        const dishes = f.dishes? f.dishes.map(date => new Date(date)) : []
        const off = f.off.map(date => new Date(date))
        return new Fantaros(f.name, soc, dishes, off);
      })
// other Component related code.
});
}

fantaroi is the list that requires monitoring for changes in order to update the view. I am seeking a solution that allows me to achieve this without duplicating the date conversion logic throughout my codebase. Any suggestions on how to approach this challenge?

Answer №1

To transform the data, utilize the pipe method and apply the necessary operations with the help of the map operator:

public getUpdate() {
  return this.collection.valueChanges().pipe(
    map(item => item.map(i => {
      const modifiedDate = i.date.map(dt => new Date(dt))
      const products = i.products? i.products.map(dt => new Date(dt)) : []
      const orders = i.orders.map(dt => new Date(dt))
      return new UpdatedItem(i.name, modifiedDate, products, orders);
    })
  );
}

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

Is there a way to modify a specific item within a useState Array in Reactjs?

Having a useState hook that stores data in the following structure: const [orderData, setOrderData] = useState({ demoData1: '', demoData2: '', demoData3: '', demoArrayData: [{itemName: '', itemNumber: ...

Is there a way to mock a keycloak API call for testing purposes during local development?

At my company, we utilize Keycloak for authentication integrated with LDAP to fetch a user object filled with corporate data. However, while working remotely from home, the need to authenticate on our corporate server every time I reload the app has become ...

Setting up Microsoft Clarity for your Angular app on localhost is a simple process

Currently, I am attempting to set up Microsoft Clarity on my Angular app to run on localhost. After creating a new project on the Microsoft Clarity portal and specifying the URL as localhost (I also tried using localhost:4200</code), I copied the scrip ...

Arrange the array based on the order of the enumeration rather than its values

Looking to create an Array of objects with enum properties. export enum MyEnum { FIXTERM1W = 'FIXTERM_1W', FIXTERM2W = 'FIXTERM_2W', FIXTERM1M = 'FIXTERM_1M', FIXTERM2M = 'FIXTERM_2M', FIXTERM3M = 'FIX ...

Guide on dividing a URL string in Angular framework

Is there a way to include a value directly in the URL, like so: http://example.com/component/july2021 I need to extract july2021 from the component and separate it into "july" and "2021". How can I achieve this? ...

Component in Angular2 encountering a null value

Unexpected situations may arise where "this" becomes null within a component. So far, I have encountered it in two scenarios: 1) When the promise is rejected: if (this.valForm.valid) { this.userService.login(value).then(result => { ...

Switching a parameter from a string to an object will cause Elasticsearch to be unable to properly index the new data structure

I have a collection of items stored in a Firebase database that I am using in conjunction with ElasticSearch for advanced queries. Recently, I had to update the structure of one of the items from a simple string, organizer: "some name", to a more complex ...

What is the best way to programmatically choose an option from a ng-select dropdown list?

My program displays a list to the user utilizing ng-select. This particular list is populated with various items: item 1 item 2 item N The user has two options when interacting with this list. They can either select an existing item or add a new one. If ...

Encountering both a CORS error and data in Angular 7

My application is using Angular 7 for the front end and Node.js (express) for the backend. The cors module in the Node.js server.js file is implemented like this: var cors = require('cors') app.use(cors()); When making an API call from the fro ...

"Error 404: The file you are looking for cannot be found on [custom company domain]. Please check

My attempts to retrieve a Google Drive file using its file ID with a service account in NodeJS have been unsuccessful. The requests are failing with an error indicating a lack of access: code: 404, errors: [ { message: 'File not found: X ...

Error occurred while creating a new instance of a generic object

I´m encountering a TypeError: type is not a constructor when attempting to convert API data into Frontend DTOs. The transformation method is as follows: transform<T>(entities: any[]) { const tableDtos = new Array<T>(); for (const ent ...

Is it feasible to utilize GraphQL subscriptions with Azure Functions?

Exploring the potential of implementing GraphQL subscriptions on Azure Functions. Unfortunately, it seems that apollo-server-azure-functions may not be compatible. Are there any other options or strategies to successfully enable this functionality? ...

Store the video file transmitted through a multipart form in Serverless Offline mode

I currently have a website built with Angular4 featuring a basic form for uploading data using ng2-file-upload. The files are sent to a Node.js-based serverless offline server where my goal is to simply save those files received from the form onto disk. A ...

Creating a custom Higher Order Component to seamlessly connect react-relay and react-router using TypeScript

Hey there! So, my Frankenstein monster project has decided to go rogue and I'm running out of hair to pull out. Any help would be greatly appreciated. I've been working on setting up a simple app with React, React-Router, React-Relay, and Typesc ...

The issue with launching a Node.js server in a production environment

I'm currently facing an issue when trying to start my TypeScript app after transpiling it to JavaScript. Here is my tsconfig: { "compilerOptions": { "module": "NodeNext", "moduleResolution": "NodeNext", "baseUrl": "src", "target": " ...

Angular 10: How to Retrieve NgForm from Projected Content

Imagine I have a component structured like this: <app-my-typical-form> <app-child-in-content></app-child-in-content> </app-my-typical-form> where the code for my-typical-form.component.html is as follows: <form #f="ngForm"&g ...

Fetching data before the Angular app is fully loaded

I need a solution to initiate a service when my app loads. If the service fails, I want to display an error message instead of continuing to load the app. I have read about using APP_INITIALIZER, but it doesn't seem to fit my requirements. In my Angu ...

What is the method for creating a new array of objects in Typescript with no initial elements?

After retrieving a collection of data documents, I am iterating through them to form an object named 'Item'; each Item comprises keys for 'amount' and 'id'. My goal is to add each created Item object to an array called ' ...

Angular has a built-in function to determine the next ID after deletion of some items

I am currently facing a situation where I have a list of contacts in a detailed view and navigating through them using the following code: <nav> <a [routerLink]="['/details', friend.id - 1 ]" *ngIf="!(friend.id == 1)"> P ...

When trying to access a property in Typescript that may not exist on the object

Imagine having some data in JS like this example const obj = { // 'c' property should never be present a: 1, b: 2, } const keys = ['a', 'b', 'c'] // always contains 'a', 'b', or 'c' ...