TypeError: Cannot read the "sort" property from undefined in SortPipe.transform, why?

I created one channel to sort the array, but when I use the channel to sort, it says an error:

Error: unclean (in promise): TypeError: cannot read the "sort" property from undefined.

pipe.ts

import { Component, NgModule, Pipe, PipeTransform } from '@angular/core';

@Pipe({name: "sortBy"})
export class SortPipe {
    transform(array: Array<string>, args: string): Array<string> {
        array.sort((a: any, b: any) => {
            if (a[args] < b[args]) {
                return -1;
            } else if (a[args] > b[args]) {
                return 1;
            } else {
                return 0;
            }
        });
        return array;
    }
}

I have included SortPipe@NgModule in ads and providers.

pipe.html

<ion-item item-detail *ngFor="let exhibit of exhibits | sortBy : 'name' 
        let i = index" name="exhibit">
    <h2>{{ exhibit?.name }}</h2>
    <h5>{{ exhibit.plan }}</h5>
    <h5>{{ exhibit.link }}</h5>
    <h5>{{ exhibit.stall }}</h5>
    <h5>{{ exhibit.description }}</h5>
</ion-item>
+4
source share
1 answer

Try wrapping your channel code in an if statement, which checks if the array has undefined, for example:

import { Component, NgModule, Pipe,PipeTransform } from '@angular/core';

    @Pipe({ name: "sortBy" })

    export class SortPipe {

    transform(array: Array<string>, args: string): Array<string> {
        if (array !== undefined) {
            array.sort((a: any, b: any) => {
                if ( a[args] < b[args] ){
                    return -1;
                } else if ( a[args] > b[args] ) {
                    return 1;
                } else {
                    return 0;   
                }
            });
        }
        return array;
    }
+6
source

Source: https://habr.com/ru/post/1681759/


All Articles