Determine if a condition is met in Firebase Observable using scan() and return the

Within Firebase, I have objects for articles structured like this:

articles
 UNIQUE_KEY
  title: 'Some title'
  validUntil: '2017-09-29T21:00:00.000Z'
 UNIQUE_KEY
  title: 'Other title'
  validUntil: '2017-10-29T21:00:00.000Z'

Currently, I am trying to fetch only those articles whose validUntil date is in the future. This is the function I've implemented in my service:

  getValidArticles(): Observable<Article[]> {
    return this.afDb.list('articles').do(console.log)
      .scan((article) => { 
        if (new Date(article.validUntil).getTime() >= new Date().getTime()) {
          return article;
        }
      })
  } 

It seems to be working fine, but I noticed that upon logging with .do(console.log), two identical objects are displayed in the console. I'm not sure if I'm approaching this correctly. Can anyone provide some insight?

Answer №1

Your current code seems to have some issues and may not be the most efficient way of handling data. Instead of downloading all data and then filtering on the client side, it would be better to filter the data directly on the server side. This way, you can avoid downloading unnecessary information that your users won't even see.

A helpful approach is demonstrated in the AngularFire2 documentation:

return this.afDb.list('articles', {
  query: {
    orderByChild: 'validUntil',
    startAt: '2017-09-29T21:00:00.000Z' 
  }
});

Answer №2

To enhance the filtering process for articles, utilize a combination of map and filter:

getValidArticles(): Observable<Article[]> {
  return this.afDb.list('articles')
    .map((articles) =>
      articles.filter((article) =>
        new Date(article.validUntil).getTime() >= new Date().getTime()));
}

If you are seeing two console.log outputs, it could be due to subscribing twice to the observable.

If server-side filtering is not supported by the AngularFire framework, consider following Frank van Puffelen's recommendation.

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

Breaking down large reducer into smaller reducers

I am currently working on a feature reducer (slice reducer) called animals. My goal is to separate these reducers into categories such as mammals, birds, fishes, and more. Initially, I thought this would be a smooth process using the ActionReducerMap. How ...

Showing JSON object in an Angular 2 template展示JSON对象在模

When I execute the following code: stanservice.categoryDetail(this.params.get('id')) .then((data) => { this.category = JSON.stringify(data.res.rows[0]); console.log(JSON.stringify(data.res.rows[0])); }) .catch((error) => { ...

What is the process for incorporating a custom action in TestCafe with TypeScript?

I've encountered an issue while trying to implement a custom action. When running tests with the new custom action, I keep receiving an error stating that my custom action is not recognized as a function. TypeError: testcafe_1.t.customActions.selectFr ...

Troubleshooting issue with getServerSideProps not functioning in Next.js while utilizing Next-redux-wrapper and TypeScript

When attempting to trigger an action as outlined in the documentation using the getServerSideProps function with the help of next-redux-wrapper store and redux-thunk, I am encountering the following TypeScript error: ts(2322): Type '({ req }: GetServe ...

Is it possible to use v-if in conjunction with a style tag to specify a different source file? Alternatively, is there a more efficient method I

I attempted the example provided below, but unfortunately, it did not function as expected. The reason behind my endeavor is that adding numerous modifiers (--tuned) to achieve the desired outcome seemed impractical. Therefore, I decided to try and link ...

What is the process for assigning a serial number to each row in the MUI DataGrid?

Initially, the server is accessed to retrieve some data. After that, additional data is added. While the data does not contain an ID, the form must still display a serial number. const columns: GridColDef[] = [ { field: 'id' ...

Include a log out option in the side menu of the ionic2 application

I am working with the sidemenu template to kick off my application. I aim to incorporate a button within the sidemenu that enables users to trigger a modal alert for confirming logout. Below is the code snippet: app.component.ts: import { Component, View ...

Tips for managing the output of an asynchronous function in TypeScript

The casesService function deals with handling an HTTP request and response to return a single object. However, due to its asynchronous nature, it currently returns an empty object (this.caseBook). My goal is for it to only return the object once it has b ...

Ways to ensure that when changes occur in one component, another component is also updated

How can I update the cart badge value in the navbar component every time a user clicks the "Add to Cart" button in the product-list component? The navbar component contains a cart button with a badge displaying the number of products added to the cart. n ...

Ways to resolve the issue with the Argument of type 'Date[]' not matching the parameter type '(prevState: undefined) in React

I've encountered an issue while trying to construct my project. The error message reads as follows: Argument of type 'Date[]' is not assignable to parameter of type '(prevState: undefined) Here's the excerpt of the code in questio ...

What is the necessity behind keeping makeStyles and createStyles separate in Material UI with TypeScript?

Dealing with TypeScript issues in Material UI has been a frequent task for me, and I find it frustrating that styling components requires combining two different functions to create a hook every time. While I could use a snippet to simplify the process, it ...

What are the steps for launching an Angular application?

Running on ubuntu 18.0.4, I had angular-cli installed. Attempting to create a new app named conFusion using the command: ng new conFusion -dir=./conFusion --style=scss. CREATE conFusion/README.md (1026 bytes) CREATE conFusion/angular.json (3666 by ...

ng serve issue persists even after resolving vulnerabilities

Can anyone assist me in resolving why I am unable to start my project after fixing 3 high vulnerabilities? I ran npm audit to identify the vulnerabilities and then used npm install --save-dev @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_em ...

Tips for determining if a key is present in local storage:

I need to set a key value, but only if it doesn't already exist. In my component1.ts file, I am assigning the key and value in the constructor. However, I want to include a condition that this action should only be taken if the key is not already pre ...

Securing Angular 2 routes with Auth Guard through canActivate

I've been searching for a solution to this problem for the past 4 hours with no luck. I have multiple Authguards set up, and I want to instruct the router to grant permission if any of them are true, rather than requiring all guards to be true. Curre ...

Find the dominant color within the project's style sheets

Is there a method to extract the main color from an angular material theme and apply it in the css files of an angular project? Within a project, we can specify the primary color in a *.scss document as shown below: @import '~@angular/material/themi ...

Distinguishing variations within subcategories that stem from a common origin

In my code example, I have two interfaces that both extend a common base interface. The "String" function takes an argument of type "StringAsset". My expectation was that if I were to call the "String" function and pass it a value of "NumberAsset", TypeScr ...

Angular Application for Attaching Files to SOAP Service

I am currently utilizing soap services to pass XML data along with file attachments. While SoapUI tool works perfectly for this purpose, I want to achieve the same functionality through Angular6 in my project. Below is a snippet of my Xml code. <soap ...

Rendering basic JSON data from the console to an HTML page using Angular

I have been utilizing openhab for sensor monitoring. To extract/inject the items(things), sensor properties, and room configuration through a web interface, I am making use of openhab's REST queries which can be found here - REST Docs. Wanting to cre ...

What are the best ways to utilize @types/bootbox and @types/jquery?

Is there a way to incorporate @types/bootbox and @types/jquery into an Angular 4 project? I attempted the following: npm install @types/bootbox and in my code, I am implementing it like so: import * as bootbox from 'bootbox'. However, I encou ...