Mapping URLs to objects in JavaScript, TypeScript, and Angular4

I have implemented a class called SearchFilter

class SearchFilter { 
   constructor(bucket: string,
               pin: number,
               qty: number,
               category: string) {
   }
}

When the user performs a search, I populate the filter into matrix params.

router.navigate(['filter', searchFilter]); //searchFilter is an instance

The resulting URL structure is as follows:

filter;bucket=MPC123;category=JOINT;qty=90;pin=9087

This functionality is utilized in another component where the parameter is mapped back to an Object of type SearchFilter. However, it is necessary to set the data types explicitly in this process.

   const params = this.activatedRoute.snapshot.params;
   const filter = this.getFilterFromParams(params);

   getFilterFromParams(params) :SearchFilter {
      const filter = new SearchFilter();
      Object.keys(params).forEach((key) => {
         switch(key) {
             case 'pin':
             case 'qty': filter[key] = Number(params[key]); break;
             default: filter[key] = params[key];
         }
      });
      return filter;
   }

Looking at the code above, a custom mapping function is used to map the parameters back to an Object. Is there a more straightforward way to achieve this or is this a commonly used pattern?

I need to rely on URLs for user-friendliness, as users should be able to share URLs with different filters.

Answer №1

To implement a static factory method, we can follow this example:

class FilterFactory {
  constructor(bucket: string, pin: number, qty: number, category: string) {
    // Constructor logic here
  }

  public static createFilter({ bucket, pin, qty, category }) {
    // Validate that pin and qty are integers before creating the filter object
    return new FilterFactory(
      bucket,
      parseInt(pin),
      parseInt(qty),
      category
    );
  }
}

We can then utilize the factory method as shown below:

const sampleParams = {
  bucket: "ABC456",
  category: "XYZ",
  qty: "75",
  pin: "3456"
};

const customFilter = FilterFactory.createFilter(sampleParams);

Answer №2

Consider utilizing the functionalities of Object.assign and the spread syntax:

createSearchFilterFromParams(params) : SearchFilter {
    return Object.assign(new SearchFilter(), params,
        ...['tag', 'quantity'].map(key => key in params && { [key]: Number(params[key]) })
    );
}

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

Setting the z-index for a JavaScript plugin

I need help with embedding the LinkedIn plugin into a website that has stacked images using z-index for layout. I have tried assigning the plugin to a CSS class with a z-index and position properties, but it hasn't worked as expected. Can anyone sugge ...

Handle errors originating from unsuccessful connections to a server named "Event" when using RxJS's fromEvent method

Using rxjs fromEvent to establish a connection with a named sse Event, I am looking to handle an Error in case of connection loss namedEvent() { try { const eventSource = new EventSource( 'adress' ); return fromEvent ...

How about mixing up your backgrounds with an overlay effect for a unique look?

Hey there, I'm currently working on adding random backgrounds to my website through an overlay, but I've hit a roadblock when it comes to displaying them. Here is the code I'm working with: .css / .php #intro { background: ...

How can an HTML5 application be configured to enable access to intranet and local files?

It's a known fact that accessing the local path of a file added using a file input field or drag-and-drop is not possible even with the new FileAPI. Whether this limitation is good, bad, or ugly is not up for debate. The FileAPI specs clearly state th ...

Switching from map view to satellite view on Google Maps allows you to see detailed aerial

Is there a way to switch from map view to satellite view on a Google Map using JavaScript after zooming in 100%? If so, how can it be achieved within the following JavaScript code? DEMO:http://jsfiddle.net/keL4L2h0/ // Load Google Map ///////////////// ...

Update the headers of the axios.create instance that is exported by Axios

I have a single api.js file that exports an instance of axios.create() by default: import axios from 'axios' import Cookies from 'js-cookie' const api = axios.create({ baseURL: process.env.VUE_APP_API_URL, timeout: 10000, headers ...

Having issues with my JavaScript code - it just won't function

I am having an issue with my JavaScript code. I don't receive any errors, but when I click the submit button, nothing happens. I have followed a video tutorial and watched it twice, but I can't seem to figure out what is wrong here. Here is the ...

Transmitted only JSON data instead of using multiform data with jQuery Ajax

When I use jQuery Ajax to send a JSON object, it ends up being interpreted as 'multiform' instead of pure JSON. How can I make sure my request is sent as a pure JSON object and not multiform? var demo = new Array("One", "Two", "Three"); $.ajax ...

An element generated using a JavaScript loop is covering another element in the layout

I am facing an issue with positioning images within a div to a span. The problem arises as the images are overlapping each other and I am uncertain about how to properly place each image when it is added. Below is the code snippet: The CSS: <style ty ...

Show the subscription response data in Angular

When utilizing the code snippets below from two different components, I am able to receive a valid response value from the subscriber. dataService.ts fetchFormData(){ return this.http.get('http://localhost:48116/RecuruitmentService.asmx/addRoleTest ...

Develop an XML document with the use of either Javascript or PHP

I have an XML file that contains information about bracelets with photo details. <bracelets> <photo filename="b1.jpg" thumbnail="a1.jpg" description="aa" /> <photo filename="b2.jpg" thumbnail="a2.jpg" description="aa" /> & ...

Incorporating sass into your Antd and Create React App workflow

Trying to combine SASS with antd and CRA has been a bit of a challenge for me. Despite following various tutorials, most of them seem outdated and result in errors. Fortunately, I stumbled upon an article that actually works smoothly link However, I can& ...

Tips for resolving the error message "cannot read property of undefined"

I've been working on coding a Discord bot and I keep encountering an error when trying to check if "mrole" has the property "app". It's not functioning as expected and I'm puzzled by why this is happening. My intention is to retrieve the te ...

Having difficulty adding a Dropdown Menu in a Pop-up Box

I am trying to incorporate a select menu inside of a popover, but every time I attempt to do so, the popover content block remains blank. The popover is associated with a side menu item called "Date History". Below is the code snippet I am using to constr ...

Guide on resolving a "res is not defined" issue in Node.js

I've been struggling to test the controller logic for a user validation module, but I keep encountering an error that says "res is not defined" even after trying to define it. How can I properly define it so that it runs through the condition statemen ...

How can you set a checkbox to be selected when a page loads using Angular?

On page load, I need a checkbox to already be 'checked', with the option for the user to uncheck it if they want. Despite trying to add [checked]="true" as recommended in some Stack Overflow answers, this solution is not working for me. <label ...

Animate the tubular geometric pathway by continuously updating its values

When creating a TubeGeometry, I supplied a SplineCurve3 / CatmullRomCurve3 path as a parameter. My goal is to update the position of each point on the path using geometry.parameters.path.points[1].y += 0.01; within the requestAnimationFrame loop. Even tho ...

The damping effect in three.js OrbitControls only activates when the mouse is pressed, however there is no damping effect once the

I find it difficult to articulate: Currently, I am utilizing OrbitControls in three.js and have activated damping for a smoother rotation with the mouse. It is somewhat effective but not entirely seamless. When I click and drag, the damping feature works ...

Accessing dynamically created AJAX controls in ASP.NET during postback operations

I am dynamically creating 2 dropdown boxes and a CheckBoxList control using AJAX callbacks to a web service (.asmx file). The server-side service generates the Dropdowns and CheckBoxList, returning the rendered html as a string which is then inserted into ...

Tips for displaying HTML elements using JSON data in React?

My goal is to dynamically render HTML elements based on JSON data using a React class that takes objects and generates a list of divs. The values inside the divs correspond to the first value in each object within the JSON. Here's an example of the J ...