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

Issue "unable to use property "useEffect", dispatcher is undefined" arises exclusively when working with a local npm package

I am currently in the process of creating my very own private npm package to streamline some components and functions that I frequently use across various React TypeScript projects. However, when I try to install the package locally using its local path, ...

Exploring the Concept of Dependency Injection in Angular 2

Below is a code snippet showcasing Angular 2/Typescript integration: @Component({ ... : ... providers: [MyService] }) export class MyComponent{ constructor(private _myService : MyService){ } someFunction(){ this._mySer ...

React 18 Fragment expressing concern about an excessive amount of offspring

Recently, I attempted to integrate Storybook into my React application, and it caused a major disruption. Despite restoring from a backup, the absence of the node_modules folder led to issues when trying 'npm install' to recover. Currently, Types ...

execute the node application using the .desktop file

Hello, I am attempting to launch an application in Linux by double-clicking it. I have come across the .desktop file as a solution (I need this method because the app will be deployed on a Raspberry Pi and users prefer not to use the terminal). Here is wha ...

Guide: Populating an MUI Autocomplete TextField using data fetched from Axios

I have created a registration form for pets which includes an MUI Autocomplete component in the text field for selecting the pet type. However, I am facing an issue when trying to pre-fill the Autocomplete component with data from the database while edit ...

The initial execution of the getDocs function may encounter some difficulties

Whenever a user connects from localhost:3000/ (which automatically redirects to /profile), I try to fetch all documents from Firebase. However, it does not work on the first attempt. Strangely, upon refreshing the page, it successfully retrieves the docume ...

Is there a way to restrict the return type of a function property depending on the boolean value of another property?

I'm interested in creating a structure similar to IA<T> as shown below: interface IA<T> { f: () => T | number; x: boolean } However, I want f to return a number when x is true, and a T when x is false. Is this feasible? My attempt ...

Tips for managing the outcome of an HTTP Post request

I am currently working with Angular 2 and Node.js, attempting to incorporate braintree into my project, which has proven to be quite challenging. My current approach involves utilizing an HTTP Post request to send back the result object from the transacti ...

What is the correct way to specify type hints for a Stream of Streams in highlandjs?

I'm currently working with typescript@2 and the highlandjs library. In the typings for highland, there seems to be a missing function called mergeWithLimit(n). This function: Accepts a Stream of Streams, merges their values and errors into a single ...

When converting to TypeScript, the error 'express.Router() is not defined' may

Currently, I am in the process of converting my express nodejs project from JavaScript to TypeScript. One of the changes I've made is renaming the file extension and updating 'var' to 'import' for "require()". However, there seems ...

Determine the chosen selection in an Angular Material autocomplete feature

Is there a method to determine which option is currently selected in the autocomplete feature so that when the user hits tab, I can automatically choose that option instead of changing the focus of the field. Check out my code snippet below: <div clas ...

Is the detection change triggered when default TS/JS Data types methods are called within an HTML template?

I'm currently updating an application where developers originally included function calls directly in the HTML templating, like this: <span>{{'getX()'}}</span> This resulted in the getX method being called after each change dete ...

Having trouble writing Jest test cases for a function that returns an Observable Axios response in Nest JS

I'm relatively new to the NestJS + Typescript + RxJs tech stack and I'm attempting to write a unit test case using Jest for one of my functions. However, I'm uncertain if I'm doing it correctly. component.service.ts public fetchCompon ...

Strange occurrences observed while looping through an enum in TypeScript

Just now, I came across this issue while attempting to loop through an enum. Imagine you have the following: enum Gender { Male = 1, Female = 2 } If you write: for (let gender in Gender) { console.log(gender) } You will notice that it iter ...

Utilizing Protractor's advanced filtering techniques to pinpoint the desired row

I am trying to filter out the specific row that contains particular text within its cells. This is my existing code: private selectTargetLicense(licenseName: string) { return new Promise((resolve => { element.all(by.tagName('clr-dg-tab ...

I am experiencing a strange situation in node.js where the `then` condition of a Promise is not being executed as expected

I am currently troubleshooting a Promise scenario and I am puzzled as to why the second then condition is failing to execute in the setup method. In my app.js code, I can see that the initialize() function is being called and it properly awaits the complet ...

Ways to exit a forEach loop when a specific condition is satisfied and obtain a string or break statement

I'm currently using Angular 14 and have been encountering some issues with a piece of code involving a ternary operator. Despite researching resources like this one and others, I haven't found a solution that works for me. The code in question lo ...

Learn the process of seamlessly uploading various document formats, videos, and previewing documents with Angular software

I am having trouble viewing uploaded files in the carousel. While I can see video and image files, other document formats are not displaying. Can someone please recommend a solution to enable viewing all types of documents as well? mydata = [] onSelect ...

Only JSON objects with a boolean value of true will be returned

I am working on returning JSON objects in JavaScript/TypeScript that have a true boolean value for the "team" property. For example, the JSON data I am using is as follows: { "state": "Texas", "stateId": 1, "team": true }, { "state": "Cali ...

I am attempting to gather user input for an array while also ensuring that duplicate values are being checked

Can someone assist me with the following issue: https://stackblitz.com/edit/duplicates-aas5zs?file=app%2Fapp.component.ts,app%2Fapp.component.html I am having trouble finding duplicate values and displaying them below. Any guidance would be appreciated. I ...