Retrieve today's bookings using a Firebase query and store them in an array

I am attempting to retrieve all bookings from firebase that match today's date.

Using an *ngFor loop in my HTML, I am displaying all returned orders.

In the firebase database, there are 7 saved bookings, with 2 of them being for today's date. Therefore, all 7 bookings are currently appearing on the screen. However, when I click the button to execute the following function, I only want to display bookings for today.

todayBookings() {

    this.ordersData = this.af.list('/orders', {
        query: {
            orderByChild: 'start',
            // equalTo: today
        }
    });
    this.ordersData.subscribe((res) => {
        this.orders = res;
    });

    this.orders.forEach(order => {

        var d = new Date();
        var curr_date = ("0" + (d.getDate() + 0)).slice(-2);
        var curr_month = ("0" + (d.getMonth() + 1)).slice(-2)
        var curr_year = d.getFullYear();
        
        var today = `${curr_year}-${curr_month}-${curr_date}`;
        var dateOfBooking = order.start.substr(0, 10);

        if (dateOfBooking == today) {
            this.todaysOrders = order;
            var index = this.orders.indexOf(order, 0);
            if (index > -1) {
                this.orders.splice(index, 1);
            }

        }

    });

    this.orders = this.todaysOrders
}

When I console log this: console.log(this.todaysOrders);

I can see the 2 bookings for today displayed in the console:

https://i.sstatic.net/iaRGu.png

Now, the challenge is how to pass these todaysOrders back into the orders array.

I attempted the following:

this.orders.push(this.todaysOrders);

However, it appended all entries and added today's bookings to the list, resulting in 9 entries instead of the expected 7. (all bookings + the 2 bookings for today).

Orders in the database

orders
 -Ko2a0zwYPQc-ocfJ1cF
   createdAt: 1499003887000
   orderId: 34681
   partySize: "1"
   requirements: "none"
   start: "2017-07-02T15:00:44+01:00"
   status: "Accepted"
   type: "tablebooking"
   + userDetails
   userId: "CQbDG6H8ENStlZiaNOGNsvbw2GL2"

   -Ko2ay19E7b17UhZ9HAf
   -Ko2pmavUZNTKdsr0pv6
   -Ko2t6cm35uOtiROeghG
   -Ko2tn6iRmkG7Y-OfAcJ
   -Ko2u5FrD5ZnIphL9Vno
   -KoBtilv2-dj-XmQSQBf

This is the complete class. I have removed other functions used for other tasks on the page.

import { Component, OnInit, AfterViewInit, ElementRef, ViewChild, OnDestroy, OnChanges } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database';
import { Router, ActivatedRoute } from "@angular/router";
import { NgForm } from '@angular/forms';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase';
import { ToastrService } from 'toastr-ng2';
import * as moment from 'moment';


@Component({
    selector: 'app-calendar',
    templateUrl: './calendar.component.html',
    styleUrls: ['./calendar.component.scss']
})

export class CalendarComponent implements OnInit, AfterViewInit, OnChanges {



    order: Array<any>;
    orders: Array<any>;
    ordersData: FirebaseListObservable<any>;

    todaysOrders: Array<any>;

    color: any;
    orderId: any;


    @ViewChild('fullcalendar') fullcalendar: ElementRef;


    constructor(public af: AngularFireDatabase, public toastr: ToastrService, public router: Router, public authentication: AngularFireAuth) {


        this.ordersData = af.list('/orders', {
            query: {
                orderByChild: 'start',
            }
        });
        this.ordersData.subscribe((res) => {
            this.orders = res;
        });


    }




    //Get Todays Bookings
    todayBookings() {

        this.ordersData = this.af.list('/orders', {

            query: {
                orderByChild: 'start',
                // equalTo: today
            }
        });
        this.ordersData.subscribe((res) => {
            this.orders = res;
        });

        this.orders.forEach(order => {

            var d = new Date();
            var curr_date = ("0" + (d.getDate() + 0)).slice(-2);
            var curr_month = ("0" + (d.getMonth() + 1)).slice(-2)
            var curr_year = d.getFullYear();
            
            var today = `${curr_year}-${curr_month}-${curr_date}`;
            var dateOfBooking = order.start.substr(0, 10);

            if (dateOfBooking == today) {
                this.todaysOrders = order;
                var index = this.orders.indexOf(order, 0);
                if (index > -1) {
                    this.orders.splice(index, 1);
                }

            }

        });

    }





}

Answer №1

To remove all orders placed today from the orders array, follow these steps:

Here is an example implementation:

if (currentDate === today) {
  this.todayOrders = order;
  var idx = this.orders.indexOf(order, 0);
  if (idx > -1) {
    this.orders.splice(idx, 1);
  }
  console.log(this.todayOrders);
  console.log(this.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

TypeScript creates a .d.ts file that contains declaration statements rather than export declarations

When compiling my code using the command tsc --p typescript/tsconfig.json --outFile "dist/umd/index.d.ts", I encountered an issue. The contents of my tsconfig.json file are as follows: { "include": ["../src/**/*"], "exclude": ["../**/*.test.ts"], ...

The type 'ElementTypes' cannot be assigned to type 'ElementTypes.word'

After recently learning TypeScript, I encountered an error that made me think I need to write a narrower type for it or something along those lines. Here is the code snippet in question: enum ElementTypes { h1 = 'H1', word = "WORD" ...

What are the best ways to troubleshoot my Angular 2 project?

I've been searching for my TypeScript files in the console, but they're not showing up. I've tried everything to debug my Angular 2 project, but no luck. I can't move forward without debugging, can anyone lend a hand? ...

Modify the parent component using dialogRef while keeping the dialog open

Within my application, there is a child dialog connected to a parent component. The parent component contains a MatTable that gets updated when the "update" button in the child dialog is clicked. The following code in the parent component is functioning p ...

Despite setting the esModuleInterop flag, I am still encountering an error with default imports

My React project with TypeScript is causing some issues. In the main tsx file, the import React from 'react' line works fine. However, in my test file, I keep getting the TS1259 error. I suspect there might be a problem with my TS/Jest/Babel conf ...

Angular 2 click event with changing function name

Even though this question seems simplistic, I'm having trouble figuring it out. As someone new to Angular 2, I've tried various combinations of {}, [], and () brackets to make the following work: <button (click)="this.action">Click me</ ...

Facing issue with Angular 17 where pipe is displaying empty data

I am currently utilizing Angular 17 with the code provided below: database.component.html @for(user of (users | userPipe:filters); track user.id) { <tr id="{{ user.id }}"> <td>{{ user.name }}</td> <td> ...

Deploy the Angular standalone component numerous times across a single page using Bootstrap

Edit After receiving input from Andrew, I have decided to adjust my strategy: Replacing survey-angular with the survey-angular-ui package Implementing a widget approach similar to the one outlined in this example Developing a single module that encompass ...

Challenges with using forRoot and other function calls in AOT compilation

Upon compiling my app, I am faced with the error message: "Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function, resolving symbol Declaran ...

It seems that Angular2 Universal is experiencing some instability as it crashes frequently with the message "[nodemon] app crashed - waiting for file

After trying to work with the starter repo from my Angular class, I've found it to be quite unstable. It seems to be working locally when hitting the same service as remote, but I keep encountering errors. I have followed all the instructions: npm r ...

The monorepo contains TypeScript files with a .js extension, causing confusion for IDEs that are unable to recognize TypeScript code within them

After cloning the React monorepo from GitHub and opening it as a new project in WebStorm IDE, I encountered an issue. It turns out that all the .js files in this repository are actually written in TypeScript, causing confusion for the IDE. For instance: / ...

Monitoring a Typescript Class's Get() or Set() function using Jasmine Spy

While working with Jasmine 2.9, I have encountered no issues spying on both public and private functions, except for when trying to spy on a get or set function at the class level. private class RandomService { public dogsHealth = 0; private get pers ...

Create a collection of values and assign it to a form control in Ionic 2

How can I set default values for ion-select with multiple choices using a reactive form in Angular? FormA:FormGroup; this.FormA = this.formBuilder.group({ toppings:['',validators.required] }); <form [formGroup]="FormA"> <i ...

Questions on deploying Angular2 to a production environment

Here are some queries regarding transitioning an angular2 web project to a production environment: While development is done on a lite server, what would be the ideal choice for production? Would another server module of nodejs be better? Considering t ...

Unit tests may not properly update the Angular Async pipe

Struggling with updating Observables using the async pipe in HTML during unit tests. I want to test not only the component itself but also ensure that child components are rendered correctly with the right Inputs. Here is a simple example where the issue ...

Tips for submitting a request following a change in the variable

I am in the process of developing a React application and I have implemented Auth0 for authentication. My goal is to initiate an HTTP request upon page refresh, but only if the variable isLoading is false. This way, I can access the user object once the ...

Merging Promises in Typescript

In summary, my question is whether using a union type inside and outside of generics creates a different type. As I develop an API server with Express and TypeScript, I have created a wrapper function to handle the return type formation. This wrapper fun ...

Angular8 Chart.js customizes the Y axis tick labels

Is there a way to dynamically adjust the Y-axis ticks in a chart.js graph? I attempted to modify them using the following commands: this.chartOptions.scales.yAxes[0].ticks.min = 10; this.chartOptions.scales.yAxes[0].ticks.max = 18; ...

Creating and managing global context with useReducer in TypeScript and React

One issue that I am facing is with the route containing a login and logout button, where the browser error states 'Property 'dispatch' does not exist on type '{}'. (home.tsx) import React, { useContext, useEffect, useRef, use ...

A TypeScript class that is a concrete implementation of a generic type

When handling a login operation, I receive an HTTP response like this: interface ILoginResponse { // ok message: string token: string; } This response structure is part of a generic response format that I intend to use for all my HTTP responses: i ...