Optimal method for populating table filter values from query string in Typescript while handling asynchronous calls

Using Typescript for Angular, I am dealing with a table that has filters in the form of drop downs. The data for each filter is retrieved asynchronously from the backend. My challenge is to load the data for all filters while setting default values based on query string parameters. To achieve this, I need to subscribe to route.queryParams.

Due to the asynchronous nature of the calls and my limited familiarity with Typescript, I am struggling to implement this correctly.

Below is an excerpt of my code:

ngOnInit(): void {
    this._service.getTypes() // Retrieve types data for filter1
        .subscribe((result) => {
            this.types = result.items;

            this._route // Subscribe to queryParams and set selected value for filter1
                .queryParams
                .subscribe(params => {
                    if (params['Type'] != undefined) {
                        this.selectedId = parseInt(params['LoadType']);
                    }
                });
        });

    this._service.getClients() // Retrieve data for filter2
        .subscribe((result) => {
            this.clients = result.items; 
            this._route // Set default value from query string for filter2
                .queryParams
                .subscribe(params => {
                    if (params['ClientCode'] != undefined) {
                        this.client = params['ClientCode'];                            
                    }
                });
        });

       ...

I find myself subscribing multiple times to queryParams for each filter, which I suspect is not the correct approach.

Answer №1

When dealing with the route.queryParams subscription, it is important to note that it does not rely on the results of the getTypes() and getClients() subscriptions. This allows you to handle them separately, subscribing to route.queryParams only once:

// Subscribe to query parameters and set selected values for filter1 and filter2
this._route
.queryParams
.subscribe(params => {
if (params['Type'] != undefined) {
this.selectedId = parseInt(params['LoadType']);
}
if (params['ClientCode'] != undefined) {
this.client = params['ClientCode'];                            
}
});

this._service.getTypes() // Retrieve types - data for filter1
.subscribe((result) => {
this.types = result.items;
});

this._service.getClients() // Retrieve data for filter2
.subscribe((result) => {
this.clients = result.items; 
});

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

The SonarTsPlugin report is coming back clean with no issues found in the Typescript files

In my current project, I am attempting to analyze an Angular application using SonarQube. This particular project consists of a mix of JavaScript and TypeScript files. During the Sonar analysis process, I have noticed that while issues are being generated ...

What can TypeScript do with high-level type functions?

Take a look at the following pseudo-code attempting to define a higher-order type function with a function-typed parameter M<?>: type HigherOrderTypeFn<T, M<?>> = T extends (...) ? M<T> : never; The syntax M<?> is not va ...

Error: Conversion of "2018-01-01-12:12:12:123456" to a date is not possible for the 'DatePipe' filter

<td>{{suite.testSuiteAttributes && suite.testSuiteAttributes.modifiedTimestamp | date: 'yyyy-MM-dd' }} </td> I am trying to display the date in the "05-Feb-2018 11:00:00 PM CST" CST format, but I keep getting an ...

Incorporate numerous values into the disabled attribute within an Angular application

Currently, I am attempting to include values in a disabled directive. In the code snippet below, you can see that I have disabled a button if a value matches System Admin. Now, my goal is to add additional values to this condition. Specifically, I would li ...

Utilizing Jest and nest.js for testing with absolute paths

Looking at my jest configuration inside the package.json: "jest": { "moduleFileExtensions": [ "js", "json", "ts" ], "moduleDirectories":["node_modules", "src" ...

Firebase V9: Uploading and Updating Documents

I am currently working on updating messages in Firebare for a chat functionality using the method below: markConversationAsSeen(conversationId: string, email: string) { const messages = collection(this.firestore, 'messages'); const q = q ...

Error message 2339 - The property 'toggleExpand' is not recognized on the specified type 'AccHeaderContextProps | undefined'

When utilizing the context to share data, I am encountering a type error in TypeScript stating Property 'toggleExpand' does not exist on type 'AccHeaderContextProps | undefined'.ts(2339). However, all the props have been declared. inter ...

Learn the process of uploading files with the combination of Angular 2+, Express, and Node.js

Need help with uploading an image using Angular 4, Node, and Express with the Multer library. Check out my route.js file below: const storage = multer.diskStorage({ destination: function(req, file, cb) { cb(null, 'uploads') }, filename: fun ...

Exploring TypeScript's Conditional Types

Consider this scenario: type TypeMapping = { Boolean: boolean, String: string, Number: number, ArrayOfString: Array<string>, ArrayOfBoolean: Array<boolean> } export interface ElemType { foo: keyof TypeMapping, default: valueof T ...

Ensure the JSON file aligns with the TypeScript Interface

I am working with a config.json file. { "profiler": { "port": 8001, "profilerCache": { "allowedOriginsRegex": ["^http:\/\/localhost:8080$", "i"] } }, "database": { "uri": "mongodb+srv://...", "dbName": "profiler", ...

Troubleshooting issues with exporting Excel in Angular 2

Having trouble exporting data in excel format using JExcelApi lib with an Angular 2 frontend and spring mvc backend? When deploying the backend to Tomcat and making a request via browser, the excel file exports correctly. However, when making the same http ...

Using Swiper in an Angular 8 application

I've been working on integrating Swiper into my Angular 8 project: . I've added a javascript file to my assets folder and included it in my angular.json. In addition, I've imported Swiper in my app.module.ts file and executed npm install @ ...

Adjust cursor location in a provided OnTypeFormattingEdits with Monaco Editor

I've implemented the following code to automatically close an XML tag when typing the '>' of an opening tag. Everything is working smoothly so far, however, I am trying to position the cursor between the tags instead of at the end of the ...

Parsing nested json objects in an angular application

I'm trying to work with a complex nested JSON structure and I need to extract and display the data in HTML. The JSON data I have looks like this: { "Test Data": [ { "First Test": { "Design Name": "testname", "Output": "1" ...

What is the best way to incorporate Tradingview's JavaScript into the render function of a React Typescript

I'm trying to incorporate some widgets into my Typescript React component. Here is the embed code export default class App extends React.Component { render(): ReactNode { return ( <div> Chart test <div className= ...

Error in VueJS/Typescript: Module 'my-module' or its type declarations are not found

Hey fellow developers! I'm currently working on a Vue2 setup with Nuxt and Typescript. I'm facing an issue while trying to install the awesome vue-slick-carousel module via yarn. When attempting to import the module in my component, Typescript th ...

Troubleshooting the issue with default useAsDefault routing in Angular 2

I have implemented Angular 2 for routing and Node for local hosting. However, I encountered an issue where using 'useAsDefault:true' for my route caused the nav bar links to stop functioning properly. The URL would redirect to http://localhost/ ...

React/Typescript/VScode - a '.tsx' extension cannot be used at the end of an import path

I have successfully converted a series of React projects to TypeScript, but I am encountering a specific issue with one non-webpack project. The error I am facing is 'an import path cannot end with a .tsx extension'. For example, this error occur ...

Using computed properties with Nuxt's `head` property can result in error messages being displayed

While utilizing Nuxt.js, I am using head() { } method to configure SEO metadata. However, when accessing computed properties within this method, Vetur displays the following message: Property 'domain' does not exist on type 'CombinedVueInst ...

What is the true function of the `as` keyword within a mapped type?

I am new to typescript and I find the usage of as confusing in the following example. type foo = "a" | "b" | 1 | 2; type bar = { [k in foo as number]: any } This example passes type checking. The resulting bar type is transformed i ...