When employing the pipe function within *ngFor, the webpage's refresh may vary, causing occasional updates

Utilizing angular2-meteor, I have already implemented pure: false. However, the pipe seems to be running inconsistently. For more details on the issue, please refer to my comments within the code.

Thank you.

<div *ngFor="#user of (users|orderByStatus)">
    {{user.status.online}}
</div>


users:Mongo.Cursor<Meteor.User>;
ngOnInit()
{
    this.subscribe('users', () => {
        this.autorun(() => {
            this.users = Meteor.users.find();
        });
    }, true);
}

import {Pipe} from 'angular2/core';

@Pipe({
    name: 'orderByStatus',
    pure: false
})
export class OrderByStatusPipe {
    transform(usersCursor:Mongo.Cursor<Meteor.User>):Array<Meteor.User> {
        console.log("OrderByStatusPipe runs");

        // (1) By only including these two lines, changes in other users' status are immediately reflected on the screen.
        // let users = usersCursor.fetch();
        // return users;

        // (2) When sorting users by their status, the page sometimes updates automatically and sometimes it does not reflect changes. 
        // To trigger an update manually, I need to click on that section of the screen.
        let users:Array<Meteor.User> = usersCursor.fetch();
        users.sort((a, b) => {
            return (a.status.online === b.status.online) ? 0 : (a.status.online ? -1 : 1);
        });
        return users;
    }
}

Answer №1

UPDATE: Good news - the bug has been successfully resolved.

It appears that the issue is related to angular2-meteor.

I have managed to find a solution by utilizing the sort function when retrieving data from Mongo. This eliminates the need for using the sort pipe.

However, you cannot directly use

users:Mongo.Cursor<Meteor.User>
with *ngFor. You must first call fetch() and use Array<Meteor.User>. Failing to do so may result in an error when the list order changes:

Cannot read property 'status' of undefined

Additionally, the list will not automatically update in the UI. To address this, you need to utilize NgZone.

Here is the finalized working code snippet:

<div *ngFor="#user of users)">
    {{user.status.online}}
</div>


users:Array<Meteor.User>;  // It's important not to use users:Mongo.Cursor<Meteor.User>
constructor(private _ngZone:NgZone) {}
ngOnInit()
{
    this.subscribe('users', () => {
        this.autorun(() => {
            this._ngZone.run(() => {
                this.users = Meteor.users.find().fetch();
            });
        });
    }, true);
}

Answer №2

It's not entirely clear what operations are happening within the calls to Meteor.users.find() and usersCursor.fetch(). However, it's possible that fetching your users should be handled separately from the filtering process. My suspicion is that part of this operation is being carried out within the filter itself (via usersCursor.fetch()?), which might be causing issues.

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

Accommodate the Angular form with a null value

In my form initialization method, I am encountering an issue when there is no email value coming from the API. This results in the error message: ERROR TypeError: Cannot read property 'value' of undefined private initForm() { this._userSer ...

Converting a String variable to a String Literal Type in Typescript: A step-by-step guide

When working with Typescript, imagine I need to call a function that has the following signature- function foo(param: "TRUE"|"FALSE"|"NONE") Is there a way to achieve something like this- var str = runtimeString() if(str === "TRUE" | str === "FALSE" | s ...

Typescript throws an error when attempting to return an array of strings or undefined from a function

I created a shallow differences function that compares two arrays of strings and returns either undefined (if the arrays are different lengths) or a string array containing matching characters at corresponding indexes. If the characters don't match, i ...

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 ...

Error: Unable to access the 'nom_gr' property of null - encountered in Chrome

<ion-col col-9 class="sildes"> <ion-slides slidesPerView="{{nbPerPage}}" spaceBetween="5"> <ion-slide *ngFor="let slide of lesClassrooms; let i = index" (click)="saveCurrentSlide(i)"> ...

What is the best way to specify a function parameter as the `QUnit` type using TypeScript in conjunction with QUnit?

In my project, which is partially written in TypeScript and licensed under MIT, I am utilizing QUnit. I have some TypeScript functions that require QUnit as a parameter, and I would like to define their types based on its interface from the typings. For e ...

Create a POST request following a GET request and handle it in Angular 2

I am in the process of developing a service that involves both GET and POST requests to be used within a component. My question is, what would be the most effective approach to achieve this? authentication.service.ts getToken() { return this.http.get ...

Attempting to invoke setState on a Component before it has been mounted is not valid - tsx

I've searched through various threads regarding this issue, but none of them provided a solution that worked for me. Encountering the error: Can't call setState on a component that is not yet mounted. This is a no-op, but it might indicate a b ...

The 'this' context setting function is not functioning as expected

Within my Vue component, I am currently working with the following code: import Vue from 'vue'; import { ElForm } from 'element-ui/types/form'; type Validator = ( this: typeof PasswordReset, rule: any, value: any, callback: ...

"Stylish form field design with outlined borders that displays a subtle hover

I am attempting to modify the background color of a mat-form-field outlined when hovering with the mouse. .mat-form-field.mat-form-field-appearance-outline.mat-form-field-outline-thick { // HOVER EFFECT background-color: $dark-blue-200; } The above ...

Why use rxjs observables if they don't respond to updates?

I have an array of items that I turn into an observable using the of function. I create the observable before populating the array. However, when the array is finally populated, the callback provided to subscribe does not execute. As far as I know, th ...

Using Angular 2 to pass a function as an argument to a constructor

How can I create a custom @Component factory where a function is called to return a component, passing the widgetName to the constructor or super constructor? export function createCustomKendoComponent(selector: string, **widgetName**: string) { @Co ...

Encountering TypeScript errors when trying to reference Angular2 within a Gulp setup

The issue at hand is: [11:16:06] TypeScript: 103 semantic errors [11:16:06] TypeScript: emit succeeded (with errors) I am currently using node v5.7.0 and npm 3.6.0 gulp -v: [11:26:58] Requiring external module babel-register [11:26:58] CLI version 3.9 ...

What is the best approach to develop a React Component Library adorned with Tailwind CSS and enable the main project to easily customize its theme settings?

Currently, I am in the process of developing an internal component library that utilizes Tailwind for styling. However, a question has arisen regarding how the consuming project can incorporate its own unique styles to these components. Although I have th ...

Are the maps intersecting within the field of vision?

I have 2 components in my angular application each showing a map from mapbox. Here is the code for one of the components: Component import { Component, OnInit } from '@angular/core'; import * as mapboxgl from 'mapbox-gl'; @Component( ...

What is the best way to insert more rows into a mat-table without disrupting the existing layout?

Having trouble adding 2 additional columns (status and buttons) after the ngfor. It seems to be disrupting the entire structure, as shown in the image below: View the Broken Table Screen Shot I am making modifications based on code from material.angular. ...

Node.js encountering an error caused by a lengthy SQL procedure execution, triggered by a POST request initiated from

Currently, my website utilizes Angular, NodeJs, and a SQL database. Most of the site's calls are made from the frontend to the backend and everything runs smoothly. However, I encountered an issue when running a stored procedure that had a longer proc ...

Encountered an error: Template parsing issues arose when integrating kendo-angular-scheduler into the app.module

I integrated the kendo-angular-scheduler into my Angular app using the following command: ng add @progress/kendo-angular-scheduler Although I have installed this module, I have not utilized it in my project yet. After compiling the code, an error message ...

Unable to execute the "install code command in PATH" command

I am encountering an issue with Visual Studio Code where the "install code command in path" option does not show up when I try to access it using Shift + Ctrl + P. My operating system is Windows 10 and I am running the latest version of Visual Studio Code. ...

What sets apart a search bar from a text field?

What distinguishes a searchbar from a textfield? Is there a way to eliminate the search icon in a searchbar? ...