Finding the number of elements in a FirebaseListObservable involves accessing the `length` property

One of the tasks in my Angular 2 application involves retrieving data from a Firebase database and storing it in a FirebaseListObservable. I have a method called getStatus that is supposed to determine the number of elements in this FirebaseListObservable. If there are elements present, I want it to return 'glyphicon-ok', and if the list is empty, I want it to return 'glyphicon-remove'. However, the code I have shared below is not working as expected.

component.ts

assignments: FirebaseListObservable<any>
submission: FirebaseListObservable<any>

ngOnInit() {
this.assignments = this._getAsnService.getAsnByCourseBatch(AuthService.courseBatch);
}

getStatus(asnDetailKey) {
  //  Searching assignment in database
  this.submission = this._db.list(`/submissions/${AuthService.uid}/`, {
    query: {
      orderByChild: 'asnDetailKey',
      equalTo: asnDetailKey
    }
  });

  //  If assignment is found return 'glyphicon-ok' else return 'glyphicon-remove'
  this.submission.subscribe(sub => {
    this.status = sub.length > 0 ? 'glyphicon-ok' : 'glyphicon-remove';
  });

  return this.status;
} 

component.html

<table class="table table-bordered" *ngIf="!isLoading">
    <tr>
      <th>Name</th>
      <th>Subject</th>
      <th>Due Date</th>
      <th>Status</th>
    </tr>
    <tr *ngFor="let assignment of assignments | async" [hidden]="filter(assignment)">
      <td> <span class="AsnName" [routerLink]="['view', assignment.$key]"> {{ assignment.AsnName }} </span> </td>
      <td> {{ assignment.subject }} </td>
      <td> {{ assignment.dueDate }} </td>
      <td> <i class="glyphicon" [ngClass]="getStatus(assignment.$key)"></i> </td>  
    </tr>
</table>

Thank you.

Answer №1

Clarification: I initially misunderstood the purpose of your request. It seems like you are looking to make an initial call to fetch assignments and then display them using ngFor. Subsequently, you want to make additional calls for each item to determine the appropriate icon to be shown in that iteration of ngFor.

Here is my proposed solution (https://plnkr.co/edit/UqHDzZMlkNQ0mXfuoIO2?p=info). Essentially, each ngFor iteration invokes the getClass() method with an async pipe. An observable is created and stored in the component at this point. However, this approach may not be very elegant as the getClass() method is called multiple times while waiting for a response in ngClass (you can observe this in the console).

There might be a more efficient way to handle this scenario. One possibility could be utilizing async/await functions (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)

Alternatively, consider pre-fetching all necessary data before rendering with ngFor. This approach eliminates the need for asynchronous responses alongside ngClass.


You could subscribe to the observable in your component (rather than using the async pipe) and determine the color after receiving the assignments.

// component.ts
getStatus(asnDetailKey){
    this.submission = this._db.list(`/submissions/${AuthService.uid}/`, {
        query: {
            orderByChild: 'asnDetailKey',
            equalTo: asnDetailKey
        }
    }).subscribe(
        res => {
            this.assignments = res;
            this.color = res.length !== 0 ? 'green' : 'red';
        },
        err => {}
    )
}

// component.html
<i class="glyphicon glyphicon-ok" [style.color]="color"></i>

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

Troubles arise when compiling TypeScript to JavaScript

I have been experimenting with TypeScript, specifically for working with classes. However, I am facing an issue after compiling my TS file into JS. Below is the TypeScript code for my class (PartenaireTSModel.ts): export namespace Partenaires { export ...

Error: The argument provided cannot be assigned to a parameter that requires a string type, as it is currently a number

Currently, I am in the process of migrating some older websites to TypeScript. However, I keep encountering a type error during the build process. The specific error message is Type error: Argument of type 'number' is not assignable to parameter ...

Utilizing a file type validator in SurveyJs: A guide

Is there a way to validate uploaded documents on a form using surveyJs and typescript with a custom validator before the file is uploaded? The current issue I am facing is that the validator gets called after the upload, resulting in an API error for unsup ...

Building a Docker image encounters an issue during the npm install process

Trying to utilize Docker with an Angular application, encountering issues during npm install within the Docker build process. When running npm install locally, no dependency errors or warnings occur. Error log from docker build: > [node 4/6] RUN npm i ...

Unable to retrieve the reflective metadata of the current class instance

Is it possible to retrieve the reflect-metadata from an instance of a class? The documentation provides examples that suggest it should be achievable, but when I attempt to do so, I receive undefined as a result. Strangely enough, when I request the metada ...

Can you explain the significance of the "@" symbol prefix found in npm package names?

While reading through the Angular Component Router documentation, I came across an npm command that caught my attention: npm install @angular/router --save I'm puzzled by the meaning of @angular/router. Is this entire string a package name? If so, ...

Tsc encounters issues when interacting with AWS services

When attempting to compile TypeScript code into JavaScript using tsc, I encountered constant crashes specifically related to AWS code within the node_modules directory. Despite my efforts to resolve the issue by adding skipLibCheck to my tsconfig file, inc ...

TypeScript compiler encountering issue with locating immutable.js Map iterator within for of loop

I am currently facing a challenge with using immutable.js alongside TypeScript. The issue lies in convincing the TypeScript compiler that a Map has an iterator, even though the code runs smoothly in ES6. I am perplexed as to why it does not function correc ...

Preventing driver closure during test suites in Appium/Webdriverio: a step-by-step guide

Currently, I am in the process of testing a react native application with a specific test suite and test cases. The test case files I am working with are: login.ts doActionAfterLogin_A.ts Test Suite: [login.ts, doActionAfterLogin_A.ts] Issue at Hand: W ...

Obtain the parameters of a function within another function that includes a dynamic generic

I am attempting to extract a specific parameter from the second parameter of a function, which is an object. From this object, I want to access the "onSuccess" function (which is optional but needed when requested), and then retrieve the first dynamic para ...

Find keys in an array based on a specified value

I need to retrieve an array of keys from an object that match a specified value ...

Unable to connect input with abstract classes at a hierarchy depth of 2 levels or more

When working on my Angular application: If a Component utilizes an Input that is defined in its immediate parent (abstract) class, everything runs smoothly. However, if a Component uses an Input that is declared in a parent class located two levels a ...

When I attempted to use jQuery to access the innerHTML of list items, I encountered the issue of it returning as Undefined

For my grocery list application created with Angular 4, I need the user to click on an item and have it added to the bookmarked section. Despite using jQuery to access the innerHTML of the li when hovered over, the value keeps returning as "undefined." In ...

Incorporating a filtering search bar in Ionic React to efficiently sort pre-existing lists based on their titles

Struggling to implement a search bar in my Ionic application has been quite challenging. I've searched for examples and tutorials, but most of them are based on Angular with Ionic. The React example in the Ionic docs didn't provide much help eith ...

Tips for passing the same value to two components using vuejs $emit

Can someone help with typing in Main, where the value can also be Test World? You can view a sample here >>> Sample The issue I'm facing is that when a user adds an item to the cart, the cart shows one more than it should. I've tried t ...

Tips on obtaining checkbox values other than "true"

Having trouble retrieving the values of selected checkboxes instead of displaying "Custom Category"? I've attempted to access the values and attributes with no success. I'm aiming to display the values of the selected checkbox. app.component.ht ...

Issue with Symbol Constructor in Typescript: [ts] The 'new' keyword can only be used with a void function

Just starting out with typescript and experimenting with the ES6 Symbol constructor. How can I address this ts lint problem without resorting to using any? const symbol = new Symbol(path); I'm trying to avoid doing this: const symbo ...

Tabulate the number of items in an array based on the month and

I have received JSON data with dates indicating the creation time of multiple parcels. I want to analyze this data and calculate the total number of parcels created in each month. I am new to this process and unsure about which thread on Stack Overflow can ...

Having difficulty adjusting the size of the ng-image-slider

I am facing some challenges in reducing the size of my video images. I have tried using the following link: https://stackblitz.com/edit/angular-jgtecl?file=src%2Fapp%2Fapp.component.html, as well as this slider: https://github.com/sanjayV/ng-image-slider ...

Angular automatically substitutes a string with the location of an image

I am currently working on developing a frame data application for a fighting game in angular/ionic, which is still relatively new to me. The app will consist of individual spreadsheets for each character showcasing the attributes of all their moves. Check ...