Utilizing AngularFire2 FirebaseListObservable in various (routed) sections of an application

Currently, I am working on developing a social platform for our sailing club using Angular2/Firebase/AngularFire. The initial module aims to enable users to search for a club member based on various criteria (filters), which are approximately 10 in number. In the process of building this feature, I had to do extensive research to find a workaround for the lack of query capabilities within Firebase. To address this challenge, I created a component to handle the filters with a child routed component responsible for displaying a list of members successfully filtered by the user. Additionally, a click handler is implemented to allow routing to the profile of the selected member. The filter component structure includes: An HTML template featuring radio buttons for selecting filters such as gender. Upon selection, the 'onFilter' method is triggered.

Filter Component

<div class="radio">
  <label>
    <input type="radio" name="genderRadios" id="genderRadioM" value="genderMale" (click)="onFilter('crewGender', 'M')">
            Male
  </label>
</div>

The 'onFilter' method's purpose is to update the filter array with the new values retrieved from the 'crewService' service.

constructor(private crewService: CrewService) {}

onFilter(myType, myParam) {
    this.crewFilter = this.crewService.updateFilter(myType, myParam);
}

This section showcases how the 'CrewService' manages filtering:

Firebase Service handler (CrewService)

updateFilter(myType, myParam){
  this.crewFilter[myType] = myParam;
  return this.crewFilter;
}

As illustrated, the 'crewFilter' array stores key:value pairs for all applied filters. The 'CrewService' service contains a method that utilizes this array to filter the AngularFire list and create a 'FirebaseListObservable' object.

@Injectable()
export class CrewService {
  private crewFilter:any[] = [];
  crews:FirebaseListObservable<any[]>;

  constructor(private af: AngularFire) {}

  getCrews() {
  this.crews = this.af.database.list('/crew').map(items => {
  const filtered = items.filter(item => {
    let match:boolean = true;
    for (let i in this.crewFilter) {
      if(this.crewFilter[i] !== 'A') {
        if (item[i] !== this.crewFilter[i]) match = false;
      }
    }
    return match;
  });
  return filtered;
}) as FirebaseListObservable<any[]>;
...

Any assistance or advice would be greatly appreciated!

Thank you

Tony

Answer №1

If you opt to utilize an observable for the filtering process, you have the potential to create a new observable that merges the most recent database list with the latest filter criteria.

The initial value of the filter can be set using a BehaviorSubject, as shown below:

import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import 'rxjs/add/operator/combineLatest';

@Injectable()
export class TeamService {

  private teamFilter:any[] = [];
  private teamFilterSubject = new BehaviorSubject(this.teamFilter);

   constructor(private af: AngularFire) {
     this.teams = this.af.database
      .list('/teams')
      .combineLatest(this.teamFilterSubject, (items, filter) => {
        const filtered = items.filter(item => {
          let match:boolean = true;
          for (let i in filter) {
            if(filter[i] !== 'A') {
              if (item[i] !== filter[i]) match = false;
            }
          }
          return match;
        });
        return filtered;
      }) as FirebaseListObservable<any[]>;
   }

  updateFilter(type, param){
    this.teamFilter[type] = param;
    this.teamFilterSubject.next(this.teamFilter);
    return this.teamFilter;
  }

  getTeams() {
    return this.teams;
  }

By creating a single composed observable in the constructor, you will only need one observable to handle both the latest data and filter changes effectively.

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

Uploading files using Remix.run: Transforming a File object into a string during the action

I'm currently developing a Remix application that allows users to upload files through a form. I have a handler function for handling the form submission, which takes all the form data, including file attachments, and sends it to my action. The probl ...

Pattern matching to eliminate line breaks and tabs

Hey there, I'm working with a string: "BALCONI \n\n\t\t\t\t10-pack MixMax chocolade cakejes" and trying to tidy it up by removing unnecessary tabs and new lines. I attempted using .replace(/(\n\t)/g, '&apo ...

Comparing strings in arrays using JavaScript

Currently, I am engrossed in a firebase project involving vuejs. My goal is to create a chart that visually represents the number of subscribers per month. The tricky part lies in accurately calculating the number of user profiles created each month. As fo ...

After incorporating lazy loading modules in Angular 8, the main component is rendered twice within the Router outlet

Shown below is the expected User Interface: https://i.sstatic.net/YYKDX.png However, the current UI being displayed is different: https://i.sstatic.net/ipBtS.png This is the content of the app-routing.module.ts file: const routes: Routes=[ {path: &apos ...

Filter Observable based on object array property

I am trying to filter an Observable and only keep the stream that has a specific property value in an array of objects inside it. For example, consider this Observable: const observable = of({name: 'agency', year: '2010', job: [ ...

Tips for working with Typescript: utilizing the default value for a non-existent computed property

When utilizing Computed Property in javascript, I can structure my code as follows const default_values = {a:"debug",b:"info",c:"warning"}; function execute(y) { let x = default_values[y] || default_values.a /* if y is no ...

Configuring NestJs with TypeORM asynchronously

I am currently facing an issue while implementing the @nestjs/typeorm module with async configuration. In my app.module.ts, I have the below setup: @Module({ controllers: [ AppController, ], exports: [ConfigModule], imports: [ ConfigModule ...

Having trouble halting the execution at specific checkpoints within an asp.net core project containing an angular 8.0 application located in a subfolder named ClientApp

Encountering difficulties stopping at breakpoints in an asp.net core project with an angular 8.0 app located in a subfolder within ClientApp. The app I need to set a breakpoint in is located at clientapp\apps\microsympan\app\src\ap ...

What is the best way to extract only IDs from a Firebase query results?

I have this code that currently returns an array of objects. I want to modify it so that it will return an array containing only the object IDs. How can I achieve this? var ref = new Firebase('https://unique-link.firebaseio.com/unique-folder&apos ...

Types with conditions but no common parameter

I am looking to define my props as either type A or B. For instance export default function App() { type Checkbox = { type: "checkbox"; checked: boolean; }; type Dropdown = { type: "dropdown"; options: Array<an ...

Can I inform the interpreter that my function in TypeScript specifically handles undefined and null values?

Consider a scenario where there is a method isEmpty that verifies if a value is empty, null, or undefined, and returns true accordingly. In TypeScript, this method may not effectively communicate to the interpreter, leading to a red underline in IDEs like ...

Using Next.js and TypeScript to Send Props to Dynamically Typed Objects

I am in the process of developing an application using Next.js with TypeScript. I have encountered an error message stating Type 'VoidFunctionComponent<ShirtDetailProps>' is missing the following properties when passing props to a component ...

Creating a Google Cloud storage access token programmatically in PythonHere is a step-by-step

I am seeking to generate a public URL for a file that I am in the process of creating within a Google function. My goal is to establish an access token: https://i.sstatic.net/7jIqI.png While I can successfully upload the file from a Python Google function ...

Introducing the latest Angular quickstart seed, now with updated dependencies to avoid npm warnings such as the deprecated [email protected

Embarking on my journey with node.js, npm, and Angular has been quite the learning curve. I am currently in the process of setting up a new Angular 2 project using their provided quickstart seed. I'm diligently following the instructions for local de ...

Express app does not receive HTTP GET parameter

When making the GET request, the response received is a 404 error code. Upon sending the request to http://localhost:3000/api/watchings/?watchItemUniqueKey=5dab6083b68bd049c0b8f9ce%7C5daf5e0c8d261e5364acd8b6, the server responds with a 404 Not Found err ...

How can deep nested properties be set in Angular without triggering a re-render of the entire component tree using the onPush change detection strategy

I recently created a simple menu component using Angular. In this menu, menu represents the ul element and each menu-item corresponds to a li. The data structure looks something like this: menu = [ { text: "level-1", children ...

Problem with Andular's datepicker functionality and local change detection

Currently, we are facing a challenge where local change detection is necessary for our component to improve performance, but it causes issues with the mat datepicker overlay. When navigating with arrow keys within the overlay and changing the month or year ...

"Error 404: The MEAN Stack has encountered a 404 Not Found error

I am currently developing a MEAN stack application and have encountered a 404 error when trying to submit a PUT request specifically for editing bookings. The editing process fails to update a particular booking. Client Side booking.service.ts getBookin ...

Implement SSL Encryption for IONIC Mobile Apps or Angular Web Applications

I am just beginning my journey in this field. Currently, I am using the IONIC framework to develop an application. The backends, which include authentication, storage, and a database, are hosted on Firebase. Additionally, I utilize some third-party APIs a ...

Caching HTTP calls with RxJS BehaviorSubject

I'm struggling to find a neat solution for cashing HTTP requests to a BehaviorSubject. I want a single method for caching and getting the value. Here's an example: @Injectable({ providedIn: 'root' }) export class DataStoreService { ...