Improving redundant code in Angular TypeScript

I'm facing a challenge with refactoring duplicated code in my project and I'm not sure where to start.

There are two methods in my code that essentially perform the same task by calling the same service (due to pagination requirements), but this repetition is making it messy. How can I improve this situation?

    getStockData(id: string): Observable<{
    searchResult: IStockResult[];
    searchCount: number;
}> {
    return this.service
        .search(
            id,
            this.service.getSearchMetaDefaults()
        )
        .pipe(
            map(response => {
                return {
                    searchResult: response, 
                    searchCount: response.meta.totalResourceCount
                };
            })
        );

Answer №1

There might be numerous sophisticated solutions to the posed query. Here are some swift tweaks I could suggest:

  1. Create distinct types for the utilized objects (for example, using TypeScript interfaces)
export interface ISearch { 
  searchResult: IStockResult[]; 
  searchCount: number; 
}

export interface IMeta {
  pagination: {
    size: number;
    index: number;
  },
  sorting: {
    order: string;
    attribute: string;
  }
}
  1. Define possible parameters with ?: and pass the argument as an object utilizing the specified types.
getData(id: string, meta?: IMeta): Observable<ISearch>

Hence, the previous calls would transform into

getStockData('some id') -> getData('some id')
paginate(1, 3, 'some id', 'some order', 'some attr') ->

const meta: IMeta = {
  pagination: {
    size: 3,
    index: 1
  },
  sorting: {
    order: 'some order',
    attribute: StockMapper.getDataForSorting('some attr')
  }
};

getData('some id', meta);
  1. Verify if the optional parameter is defined utilizing the nullish coalescing operator (??) before utilization.
const meta = meta ?? this.service.getSearchMetaDefaults();

Merging all components together

getData(id: string, meta?: IMeta): Observable<ISearch> {
  const meta = meta ?? this.service.getSearchMetaDefaults();

  return this.service.search(id, meta).pipe(
    map(response => ({
      searchResult: StockMapper.fromStockResource(response),
      searchCount: response.meta.totalResourceCount
    } as ISearch))
  );
}

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

Tips for triggering a click event automatically after a 2-minute delay in ReactJS using TypeScript

I need assistance automating a button's onClick function to execute after a 2-minute delay. The current button invokes the handleEventVideos() function. What is the best way to automatically trigger the button click after 2 minutes? I had tried creat ...

Arranging Select Dropdown Options in a Specific Order using Angular 7 and Typescript

My select dropdown is populated dynamically with options fetched from a service using *ngFor. I am looking to customize the order of these options. Can this be achieved through Angular code? The array structure is as follows: console.log(this.paymentTyp ...

The specified file 'node_modules/bingmaps/types/MicrosoftMaps/Microsoft.Maps.d.ts' cannot be treated as a module

Currently utilizing the official npm package for bingmaps with angular 7 (cli). I have followed the configuration instructions outlined in the npm documentation, and I am successfully loading the basic bing map. In my component.ts file, I included the ...

Benefits of Angular Signals - Why is it advantageous?

I'm grappling with the concept of Angular Signals and their benefits. While many examples demonstrate counting, I'm curious about why signals are preferable to using variables like myCount and myCountDouble as shown below? Check out my code on S ...

It's conceivable that the item is 'null'

I am encountering Typescript errors in my code that are related to parameters I am receiving from a previous screen. This is similar to the example shown in the React Navigation documentation found at https://reactnavigation.org/docs/params/. interface Pix ...

Encountering difficulties accessing props while invoking a component in React

In my project, I've created a component called FilterSliders using Material UI. Within this component, I passed a prop named {classes.title} by destructuring the props with const { classes }: any = this.props;. However, when I try to access this prop ...

Steps for building a custom component using MUI as a foundation

My current approach: import React from "react"; import {useHistory} from "react-router-dom"; import {Button, ButtonProps} from "@mui/material"; type Props = { label?: string } & ButtonProps; export const NavBackButton = ...

Stopping HTTP redirection in Angular 2

Attempting to simulate user login using Angular2 Http. Let's describe the situation below. There is a PHP application where users can log in through http://sample.com/login.php URL (a form exists with username and password input, users must fill in ...

Validation of route parameters in Angular 4

Currently, I have a predefined route that includes a parameter called userID. { path: "edit/:userID", component: EditUserComponent, canActivate: [AuthGuard] }, Within the edit-user-component.ts file, the following logic is implemented: ...

`Warning: The alert function is not working properly in the console error

I am currently working on integrating otp functionality into my Ionic 3 project. I am facing an issue where I am able to receive the otp, but it is not redirecting to the otp receive page due to a specific error. Below is the console error that I am encou ...

Encountering an error when utilizing Angular Animation with Bootstrap -> Issue arises from attempting to read properties of undefined (specifically 'box-sizing')

To access the source code of Git, visit https://github.com/codezj/exampleAppAnimation. I recently developed a method to extract Bootstrap CSS and utilize it as CSS in Angular. However, I encountered an error while running the Angular project: Uncaught Typ ...

Guide to navigating to a specific route based on location in a Node.js Express application

Currently, I am integrating the official i18n library to localize my Angular Universal application and utilizing a proxy to deliver the localized versions. The app is functioning properly when there is a language specified in the URL (e.g: /en/page), but e ...

Retrieve information using Observables just once in Angular 2

One of my Angular 2 components relies on a service that fetches customer data from a Web API and returns an Observable: getCustomers() { return this.http .get(this.baseURI + this.url) .map((r: Response) => { let a = r.jso ...

Guide to initiating an Angular 6 project using Angular CLI version 7.3.3

My current Angular CLI version is 7.7.3, but I need to create an Angular 6 project using it. When I use the CLI command 'ng new project_name', it only allows me to create an Angular 7 project. Is there a way to force creating an Angular 6 project ...

The revalidation process in react-hook-form doesn't seem to initiate

Stumbled upon a code example here Decided to fork a sandbox version (original had bugs and errors) I am trying to implement custom validation callbacks for each form input element by providing options in the register function, but the validate is only tr ...

Searching for a value within an array of objects in Typescript/Vue 3. The objects are of an unknown data type

Is there a way to fix this TypeScript error? To provide some background, I am working with the Vue 3 Composition API where I need to use the result to determine if a default option value should be displayed as <option ... selected v-if="!isMatch&qu ...

main.js:1 ERROR TypeError: Unable to access property 'querySelectorAll' of null

I am currently using Chartist in conjunction with Angular to generate charts. However, I am encountering a problem where the charts do not display when the server is running, and an error appears on the console. Strangely enough, refreshing the page caus ...

Utilizing feature flags for Angular modules to enable lazy loading

Can we dynamically change the lazy loaded module based on a specific flag? For instance, loading module A if the flag is active and module B otherwise. The crucial aspect is that both modules should use the same path. Approach #1 - dynamic loadChildren() ...

Instead of the type definition file, navigate to the TypeScript source file within VS Code

A unique npm library I developed is utilized in various main projects, with all the sources stored within a /src directory and written in TypeScript. The compiler options listed in the tsconfig.json file include "sourceMap": true and "outDir": "dist". Addi ...

Trouble with Typescript in VSCode made easy

Setting up a VSCode environment for working with TypeScript v2.03 has been challenging. Beginning with a simple vanilla javascript snippet that can be tested in node via the integrated terminal. function Person() { this.name = ""; } Person.prototy ...