Retrieve a collection of Firebase records using a specific query parameter

I'm currently developing a web app with Angular 2 and facing an issue with retrieving data from Firebase based on specific conditions in the child node. Here's how my Firebase structure looks like: I need to extract the entry for the one with approverEmail set as [email protected] and status as 0 (both conditions must be met simultaneously).

{
  "BugList" : {
    "Company 1" : {
      "-Kbne6WxelgI6Qv9T0eP" : {
        "approverEmail" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a0c1d0d0d2cfd6c5d291e0cdc1c9cc8ec3cfcd">[email protected]</a>",
        "firstName" : "Jack",
        "lastName" : "Daniels",
        "noteToApprover" : "Gooday mate",
        "status" : 0,
      },
      "-Kbne6WxelgI6Qv9T0QP" : {
        "approverEmail" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="04657474766b726176364469656d682a676b69">[email protected]</a>",
        "firstName" : "Tom",
        "lastName" : "Riddle",
        "noteToApprover" : "Howdy",
        "status" : 1,
      }
    }
  },
}

My current approach involves using angularFire2, which lacks sufficient documentation on this particular issue. This is where I'm at right now and could use some guidance.

forms.service.ts
getPendingApproval() {
    var currentUser: User = this.userService.getCurrentUser();
    const queryList = this.af.database.list('/BugList/' + currentUser.company, {
        query: {
            // email field match currentUser.email && status == 0 
        }
    });
}

And in my app.component.ts

getList() {
    this.list = this.formsService.getPendingApproval()
  }

This is the snippet of code from my forms.service.ts

@Injectable()
export class FormsService {

    constructor(private af: AngularFire, private userService: UserService) { }

    saveToFirebase(bug: Bug) {
        const bugRef = this.af.database.list('/BugsList/' + bug.companyName);
        return bugRef.push(timesheet)
    }


    getPendingApproval() {
        var currentUser: User = this.userService.getCurrentUser();
        const queryList = this.af.database.list('/BugsList/' + currentUser.company, {
            query: {

            }
        });
    }
}

Answer №1

In order to query multiple fields, you can filter the second field after retrieving the pre-filtered list.

For example, here is a sample query:

query: {
  orderByChild: 'email', // specify field name
  equalTo: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1b6f7e686f5b6c7e79357f7e">[email protected]</a>' // search criteria
}

To filter using a Subject:

const filterSubject = new Subject(); // import {Subject} from 'rxjs/Subject';
const queryObservable = af.database.list('/items', {
  query: {
    orderByChild: 'email',
    equalTo: filterSubject
  }
});

// subscribe to changes
queryObservable
   .map(qis => qis.filter(q => q.status == 0)) // FILTER HERE FOR STATUS
   .subscribe(queriedItems => {
      console.log(queriedItems);
   });

// trigger the query
filterSubject.next('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a0d4c5d3d4e0d7c5c28ec4c5">[email protected]</a>');

// re-trigger the query!!!
filterSubject.next('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="224a574a5762454f434b4e0c414d4f">[email protected]</a>');

Find more information in the documentation: https://github.com/angular/angularfire2/blob/master/docs/4-querying-lists.md

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

tips for deleting an element from an object in angular

I'm dealing with an object that looks like this: { first_name: "acasc" last_name: "acsac" email: "acac" mobile_number: "acac" password: "acac" confirm_password: "acac" } Here's what I need to do: If the password a ...

Can you explain the significance of this particular method signature in the TypeScript code snippet shown above?

Referencing the ngrx example, we encounter the code snippet for the method store.select, which has a complex signature with two arrows. What is the significance of this method signature? The interface definition in the type file presents the following sig ...

retrieving information from an array of objects within a nested JSON array

Struggling to extract information from an API set. When viewed in Postman / Insomnia, the body looks like this: { "responses": { "log": [ { "id": 123, "date": "2022-01-01T01:12:12.000Z", ...

What is the syntax for declaring a function type with an optional parameter in Typescript?

I have a function with optional parameters that I am passing down to another component. execute = (option: string = 'default'): void => { // ... } In the receiving component, there is a property called executeFunction where I intend to assi ...

Best practices for transitioning a project from TypeScript 3 to TypeScript 4?

I am looking to upgrade my large monorepo, which was built using lerna, React, and TypeScript 3.7 around 2-3 years ago. My goal is to update it to TypeScript 4.8. Are there any tools available that can help me analyze and identify potential breaking chan ...

Parsing of the module has failed due to the presence of an unexpected character '' while attempting to import a video file

Trying to create a video player in NextJS using TS. I brought in a video file from my src/assets folder and encountered an error. Error - ./src/assets/video.mp4 Module parse failed: Unexpected character '' (1:0) You may need an appropriate load ...

"Encountering issues with Angular2's FormBuilder and accessing nested object properties,

As I dip my toes into TypeScript and Angular2, I find myself grappling with a nested object structure in an API. My goal is to align my model closely with the API resource. Here's how I've defined the "Inquiry" model in TypeScript: // inquiry.ts ...

Changing the Class of an Element in a Different Component with Angular 2+

Currently in a project utilizing Angular 4, I have implemented two components: app.component and other.component Within app.component.html, there exists a div with the name attribute myClass. <div class="myClass"></div> In the other.componen ...

TypeScript causing issues when multiple selectors are used

Currently, I have a function that allows me to search for HTML elements based on text content: function findElementsByText(text: string): HTMLElement[] { const selectors = 'button' // This conditional statement ensures that an empty text quer ...

Exporting a Middleware member is essential for defining Koa middleware type definitions

Currently utilizing KoA with Typescript and incorporating the KoA middleware KoA-static and KoA-bodyparser. Ensuring that I have installed the type definition packages @types/koa, @types/koa-bodyparser, and @types/koa-static. However, upon running tsc, enc ...

Is the variable empty outside of the subscribe block after it's been assigned?

Why is a variable assigned inside subscribe empty outside subscribe? I understand that subscribe is asynchronous, but I'm not sure how to use await to render this variable. Can someone please help me and provide an explanation? I am attempting to retr ...

Guide to making a Typescript type guard for a ReactElement type

I'm currently working with three TypeScript type guards: const verifyTeaserOne = (teaser: Teaser): teaser is TeaserOneType => typeof teaser === 'object' && teaser.type.includes('One'); const validateTeaserTwo = ( ...

What is the process for generating a fresh PSBT transaction using bitcoinjs-lib?

This is the code I've been working on import * as bitcoin from 'bitcoinjs-lib' const NETWORK = bitcoin.networks.regtest; const psbt = new bitcoin.Psbt({ network: NETWORK }); function p2shAddress(node: bitcoin.ECPairInterface): string { c ...

Guide to importing a class property from one file to another - Using Vue with Typescript

Here is the code from the src/middlewares/auth.ts file: import { Vue } from 'vue-property-decorator' export default class AuthGuard extends Vue { public guest(to: any, from: any, next: any): void { if (this.$store.state.authenticated) { ...

Guide to successfully passing a function as a prop to a child component and invoking it within Vue

Is it really not recommended to pass a function as a prop to a child component in Vue? If I were to attempt this, how could I achieve it? Here is my current approach: Within my child component - <template> <b-card :style="{'overflow-y&apo ...

Issues with the ionViewDidLoad() function?

Having some trouble implementing Email Authentication in my project. The method ionViewDidLoad is not being recognized. I also tried using the method ionViewWillLoad() but that didn't work either. Any ideas on what might be causing this issue? Here&a ...

Setting a variable based on the stage of its deployment in a DevOps environment: What you need to know

Is there a way I can easily update a variable in a React app based on the stage of an Azure DevOps release pipeline? For instance, if I have dev, QA, and production stages set up, and I want to change the client ID in the auth configuration for each envi ...

retrieve a collection of objects using Angular CLI

Hey there, I'm currently working on fetching data using a get request in Angular. My Apartment class is structured as follows: export class Apartment { id: number; address: string; constructor(id: number, name: string) { this.id = id; ...

What are the benefits of incorporating component A into component B as a regular practice?

I am considering creating an instance of Component A within Component B, but I'm unsure if this is a best practice in Angular or if it will just cause confusion. Component A: This component generates a modal window asking the user to confirm file de ...

The Angular Material Autocomplete component fails to show items upon upgrading the angular/material package to the newest version

Issue with Angular Material Autocomplete component not displaying items after updating angular/material package to the latest version. The autocomplete was functioning correctly with "@angular/material": "^2.0.0-beta.10" but encountered issues when update ...