Tips for enhancing parameters in TypeScript/Angular methods

I'm working with a function that has multiple parameters:

public find(
    cadnum: string,
    pagesize: number,
    startid?: string
  ): Observable<any> {
    let url = "";

    if (cadnum) {
       url+= "?cadnum=" + cadnum;  
    }

     if (pagesize) {
       url+= "&pagesize=" + pagesize;  
    }

 if (startid) {
       url+= "&startid=" + startid;  
    }

    return this.httpClient.get(url);
} 

It seems like there may be a better way to handle checking and concatenating the URL string, especially when dealing with more parameters. Any suggestions on how to improve this process?

Answer №1

The simplification of the above code snippet can be seen below:

return this.httpClient.get(url, { 
  headers: { 'Content-Type': 'application/json' },
  params: {
    cadnum, 
    pagesize,
    startid,
  },
});

Another approach is to consolidate the parameters of the find function into an object before sending it to the httpClient:

const params: HttpParams = {
  cadnum, 
  pagesize,
  startid,
  // other parameters 
};

return this.httpClient.get(url, { 
  headers: { 'Content-Type': 'application/json'},
  params, 
});

Answer №2

Utilize an Object as a parameter and iterate through its attributes

// Transforming an object into HttpParams
// Found this function in JHipster :p
const createRequestOption = (params?: any): HttpParams => {
    let options: HttpParams = new HttpParams();
    if (params) {
        Object.keys(params).forEach(key => {
            if (req[key] != null) {
                options = options.set(key, req[key]);
            }
        });
    }
    return options;
};

public find(params? :any): Observable<any> {
    const url = 'http://...';
    const options = createRequestOption(params);
    return this.httpClient.get(url, { params: options});
}

If you prefer strong typing, this approach should also work

public find(params: {
    cadnum: string,
    pagesize: number,
    startid?: string
}): Observable<any> {
    const url = 'http://...';
    const options = createRequestOption(params);
    return this.httpClient.get(url, { params: options});
}

Answer №3

Revise your function to accept an array as a parameter, then iterate through each value to construct the corresponding URL.

public generateURL(
    parameters: any[]
  ): Observable<any> {
    let url = "";

parameters.forEach(function (value) {

if (value) {
       url+= "&" + value + "=" + value;  
    }
});

}

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

What are the methods used in TypeScript to implement features that are not available in JavaScript, despite TypeScript ultimately being compiled to JavaScript?

After transitioning from JavaScript to TypeScript, I discovered that TypeScript offers many features not found in JS, such as types. However, TypeScript is ultimately compiled down to JavaScript. How is it possible for a language like TypeScript to achie ...

Angular 9 TestBed RouterTestingModule: Exploring the router.url Readonly Property

While transitioning from Angular 8 to Angular 10 in stages, I encountered an issue when upgrading to version 9. All of my TestBed.get(Router).url calls started throwing errors because the property had become read-only. For instance, the code TestBed.get(R ...

Transform the values in an object using TypeScript without losing type information

Can TypeScript map an object's values to another type based on the actual type of each entry in the result? To better explain my goal, consider the following scenario: const obj = { a: 1, b: true, c: "foo" } const result = toFunctions(o ...

What is the best way to display API error messages to the user?

When a user tries to upload a file that is not an image, I need to display the error message returned from a REST API. The JSON response received from the API will look something like this: { "publicError": "Could not be uploaded, it is not an image! ...

Using TypeScript to access the outer "this" from a literal getter

When attempting to access the outer "this" scope in Typescript while using getters and setters in object literals, it seems there is no straightforward method. Take for example the code snippet below: class Report { stuff: any[]; options = { ...

Angular - Dropdown menu fails to display options

I encountered an issue with the JSON response from my Angular-12 API endpoint: { "message": "vehicle Model Detail.", "error": false, "code": 200, "results": { "vehiclemakes": [{ ...

Using Angular to create a Mat table with the ability to select multiple rows

Trying to add shift click feature to a sorted MatDataTable using angular and typescript. When a click event occurs on the table, the selected row is stored. If a shift click is detected, it should select rows between the last selected and the current row ...

Performing a `npm install` within a subfolder of a Git repository

Hello there, I've developed an angular library and successfully uploaded it to a private gitlab repository. Now, I'm looking to integrate it into another project. I attempted to import it by adding the following line to my package.json file: "m ...

steps for setting up firestore database

Hey there, I'm trying to retrieve data from Firestore within a cloud function. To initialize Firebase, I have a file called firebase.ts: import * as admin from "firebase-admin"; import { getFirestore } from "firebase-admin/firestore&quo ...

Is there a way to transform a pair of dates from a JSON string into an array within a JSON

I am facing an issue where I need to send a JSON format like this to the backend: {"n":"dsad","t":"asda","term":"2021-06-26, 2021-06-30"} However, I actually need to send the "term" field in an a ...

Utilizing a fixed array as the data source for a mat-table

I am currently working on implementing the Angular Material table into my project. I am encountering an issue when trying to define the [dataSource]="data", even though I am using code similar to the examples provided. My question may seem basic, but my t ...

Error message: The variable "str" is trying to be accessed from null typeScript

Recently I started delving into TypeScript and encountered a problem that's been giving me trouble. Whenever I try to retrieve my location and utilize the Google Maps API to gather street and city information, an error message pops up saying "Cannot r ...

Using the Angular routerLink feature may fail to properly navigate to the intended component

I'm encountering an issue with the routing in my Angular2 application. Despite following the guidelines outlined here, my routeLinks are not functioning as expected. Below is my routing configuration: const routes: RouterConfig = [ { path:'h ...

Issue: The component factory for GoogleCardLayout2 cannot be located

Recently I've been working on an Ionic 3 with Angular 6 template app where I encountered an issue while trying to redirect the user to another page upon click. The error message that keeps popping up is: Uncaught (in promise): Error: No component fac ...

Changing the type of an object's property in TypeScript on the fly

I am working on a TypeScript function that is designed to dynamically modify the property of an object. Here is the function: const updateProperty = (value: any, key: keyof Type1, obj: Type1) => { obj[key] = value; } Below is the definition of "Typ ...

Tips for evaluating the RouteConfig and additional decorators within an Angular 2 Component

I'm facing a challenge in writing unit tests for my Angular 2 component. Specifically, I need to write a test that checks if the RouteConfig's path is set to '/documents'. Additionally, I want to verify if the template contains <rout ...

Angular 9 Problem: Facing difficulties launching the primary application

Looking for assistance with a technical issue I am trying to set up an initial application on my Windows 10, 64-bit machine following the instructions provided in but I am encountering a problem. OS: Windows 10, 64-bit Issue: The command npm install is ...

Issues with NativeScript WebView displaying HTML file

Having trouble loading a local HTML file into a webview in my NativeScript (typescript) application. Despite using the correct path, it's not loading and instead shows an error. <WebView src="~/assets/content.html" /> An error message stati ...

Having trouble utilizing the ng-Command in Angular?

Currently, I am attempting to set up Angular in a vagrant-box environment. npm install -g @angular/cli Unfortunately, I encounter an error while trying to use the client: The program 'ng' is currently not installed. You can install it by typin ...

Angular 7's masonry overlay technique

I decided to implement a masonry design in my Angular application using the ngx-masonry package found here: https://www.npmjs.com/package/ngx-masonry However, I encountered an issue where some items are overlapping, as shown in this image: https://i.sstat ...