Encountering a sort error in Angular 8 when attempting to sort an Observable

I am struggling to organize an observable that is retrieved from a service using http.get. I have attempted to sort the data both from the service and in the component after subscribing. However, I keep encountering the error "Sort is not a function". As a newcomer to Angular, I am having trouble with sorting. Any assistance would be greatly appreciated. Thank you.

JSON sample

"data": [

    {
        "codeValue": 2,
        "codeType": 145,
        "description": "ASSIMILATION"
    },
    {
        "codeValue": 3,
        "codeType": 145,
        "description": "BANKRUPTCY"
    },
    {
        "codeValue": 4,
        "codeType": 145,
        "description": "BID TENDER"
    },

event.interface.ts

export interface IEventInterface {
codeValue: number;
codeType: number;
description: string;

}


Service.ts
getEventType():
{

    return this.http.get<IEventInterface[]>('/gpscaservices/v1/system- 
 descriptions?codeType=145&codeValue=');

}

Create.Component.ts

orderedEvent: any;
eventTypes: any;

this._dataService.getEventType().subscribe({
next: (response: IEventInterface[]) => {
            this.eventTypes = response  ;
            this.sortBy('description');
        }

sortBy(field: string ) {
               this.eventTypes.sort((a: any, b: any) =>{
        if (a[field] < b[field]) {
            return -1;
        } else if (a[field] > b[field]) {
            return 1;
        } else {
            return 0;
        }
    });

        this.orderedEvent = this.eventTypes;

Create.Component.html

nx-option *ngFor="let eventType of orderedEvent.data" 
[value]="eventType.codeValue">
{{ eventType.description }}
/nx-option>

Answer №1

Perhaps you overlooked the data field.

sortBy(field: string ){
  this.eventTypes.data.sort((a: any, b: any) => {
    if (a[field] < b[field]) {
      return -1;
    } else if (a[field] > b[field]) {
      return 1;
    } else {
      return 0;
    }
  });

  this.orderedEvent = this.eventTypes;
}

It's advisable to specify a clear type instead of using any.

export interface EventData {
  data: IEventInterface[]
}

orderedEvent: EventData;
eventTypes: EventData;

Answer №2

If you want to customize your sorting function, consider implementing it like this:

sortEventTypes(sortString : string){
   this.eventTypes.sort(function (a, b) {
     return a[sortString] - b[sortString];
  });
}

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

Filtering strings with the same suffix

Here is a code snippet I am working with: type RouterQuery = keyof AppRouter['_def']['queries']; This code defines the following type: type RouterQuery = "healthz" | "post.all" | "post.byId" | "catego ...

Having difficulty sending the [ctrl][p] keys to a page that is not using Angular framework

Working with protractor version 5.1.2, Angular 5, and typescript 2.4.2 When attempting to trigger a 'print' function using the shortcut keys '[ctrl][p]' in protractor on a non-angular page, I encountered an issue. Within my protractor ...

Using JQuery within Angular 4 is a valuable tool for enhancing the functionality

As a newcomer to Angular, I am experimenting with using jQuery alongside Angular 4. In my search for information, I stumbled upon this question on Stack Overflow. Inside the question, there was an example provided that can be found here. However, when att ...

Using async-await in canActivate() within Angular 7

I am currently working on a code that verifies whether the browser contains user information. If not, the browser will make an API call to retrieve the user information from the server. Only users with valid information are granted access to navigate to di ...

Exploring the world of Jasmine and Angular: How to effectively mock nested methods within the Class being tested

Hello esteemed community... I have encountered a perplexing issue that appears straightforward, but has eluded my attempts at resolution... The challenge I am facing involves testing a Controller-Class in Angular. This particular codebase is laden with d ...

Issue with TypeScript error encountered when attempting to save data locally using React-Redux and LocalStorage

Currently, I am delving into the worlds of React-Redux and TypeScript. Within my small app, I aim to utilize localStorage to store data locally. I attempted to address this based on information from this particular answer, but ran into a TypeScript erro ...

Incorporating an Angular 2 application into HawtIO as a plugin

Can we integrate an entire Angular2 application as a plugin in HawtIO? By doing this, we aim to leverage HawtIO as the main container for our OSGi applications, each with its own user interface, allowing us to easily detect and display each UI web app with ...

I'm looking for ways to incorporate TypeScript definition files (.d.ts) into my AngularJS application without using the reference path. Can anyone provide

I'm interested in leveraging .d.ts files for enhanced intellisense while coding in JavaScript with VScode. Take, for instance, a scenario where I have an Angular JS file called comments.js. Within comments.js, I aim to access the type definitions prov ...

Playing noughts and crosses with the minimax strategy

I am struggling with understanding the minimax algorithm and have been working on it for 2 days without success. Can anyone take a look at my code and help me identify any errors? export default class TicTacToeController { /*@ngInject*/ constructor($s ...

Using a variable within an Angular 2 Component provider

Is it possible for a component to offer a service based on its inputs? In my situation, my component relies on a service provided by another firebase service, and I am looking to have the component create a new firebase service with a child element, allowi ...

Installing Angular Flex has been challenging for me

Encountering an error while running npm install @angular/flex-layout. Does anyone know what this means? I tried using --force, and the installation completed successfully. However, upon starting up the project, it seems to be broken. gonzalo@gonzalo-Inspir ...

The problem with the Custom Select Component: Error Arises When Utilizing the Generic Type <T,> with a Comma as Opposed to <T> Without a Comma

I recently developed a unique custom select component that extends the standard HTML select element. During the process, I made use of a generic type to accommodate a wide range of data types, but encountered an unexpected error. The issue seems to persist ...

How to Upload Images in Angular 10 Using ngFor

Is it possible to change the image source when uploading an image using ngFor loop? <div *ngFor="let product of products" > <input type='file' #fileInput (change)='onFileUpdate($event,product)' style="display: ...

Error message: "The property is not found within the specified type when using the OR operator with

Within my Angular component, I am faced with a challenge involving an Input that can be one of two types. @Input() profile: UserProfileDetails | BusinessProfileDetails; The structure of the profile template is straightforward and I want to avoid duplicati ...

What is the best way to extract a property if it may be undefined?

Can anyone help with this TypeScript error I'm encountering during build time? Any suggestions would be appreciated. Error Message: TypeError: Cannot destructure property 'site' of '(intermediate value)' as it is undefined. export ...

The Chrome developer console is alerting that the Typescript file needs to be updated and is currently

Just made an update to my typescript file in my app and ran it. Source maps are enabled. When I check in Chrome by pressing F12 and browsing to the script, I see the .ts file without the recent function I added, but the .js file does have it. I tried fo ...

Having trouble resolving the typescript package while integrating with another module

Attempting to develop a basic npm package with TypeScript and bundle it using webpack. When trying to use the package in another module, such as a react application named 'module A.' Within module A, the 'myLibrary' package is installe ...

Checking the types of arrays does not function properly within nested objects

let example: number[] = [1, 2, 3, 'a'] // this code block correctly fails due to an incorrect value type let example2 = { demo: 1, items: <number[]> ['a', 'b'], // this code block also correctly fails because of ...

Setting the paths property in a project with multiple tsconfig.json files: a step-by-step guide

My file structure is organized as follows: |__ app1/ | |__ tsconfig.json |__ utilities/ | |__ files.ts |__ base-tsconfig.json I have defined the paths property in base-tsconfig.json like this: "compilerOptions": { "baseUrl": ".", "pa ...

What is the Angular Observable async pipe used for?

Imagine having a Rest API that lists events. POST [203]: returns an array of events. POST [404]: indicates no data found. Below is the code snippet: export function httpFetchRetry<T>(source: Observable<T>): Observable<T> { let errorSc ...