Angular makes it easy to extract multiple parameters from a URL

In the process of developing a basic Angular application using TypeScript, I have encountered an issue.

Within my project, there is a URL structure like this:

www.example.com/api/1/countries/Italy/

My goal is to extract the values 1 and Italy from this URL and store them in variables.

I attempted to utilize ActivatedRoute as shown below:

 ngOnInit() {
    this.router
        .queryParams
        .subscribe(params => {
           this.id = +params[''];
           this.country = +params[''];
        });
}

The private variables id and country are where I intend to store the extracted values from the URL. However, I am unsure about the next steps to take...

What additional actions do I need to carry out?

Answer №1

When looking at your URL example, it is clear that query parameters are not being utilized. In order to retrieve values from the ActivatedRoute, you can use code similar to the following:

 this.id = this.route.snapshot.paramMap.get('id');
 this.country = this.route.snapshot.paramMap.get('country');

This code assumes that your routes have been configured with parameters named id and country, for instance:

 {path: 'api/:id', component: CompA}
   ...
 {path: 'countries/:country', component: CompB}

Answer №2

One way to retrieve a url is by utilizing the DOCUMENT object and processing it accordingly.

component.ts

import { DOCUMENT } from '@angular/platform-browser';

  constructor(@Inject(DOCUMENT) doc: any) {
    console.log(doc.location.href);
  }

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

How can I use Angular2 to draw a square [input] number of times?

I need to create a specific number of squares within a container using Angular2. Can you please provide me with a straightforward example, preferably utilizing canvas? Currently, I have converted webpack starter for use with Angular: This is the code ins ...

Substitute Customized Interface Type Identifier

I am working on creating a versatile function interface for functor map while respecting the provided interface. In the code snippet below, my goal is to ensure that the value of mb is of type Maybe<number>, rather than the actual type Functor<num ...

Displaying notification in Ionic 2

Whenever I click on the register button, if I fill out all the fields I am taken to the regsuccess page. Otherwise, I receive a message saying to fill in all required fields. However, I want to display an alert message using Ionic2 and TypeScript. HTML: ...

Accessing an unregistered member's length property in JavaScript array

I stumbled upon this unique code snippet that effectively maintains both forward and reverse references within an array: var arr = []; arr[arr['A'] = 0] = 'A'; arr[arr['B'] = 1] = 'B'; // When running on a node int ...

Issue regarding custom CSS implementation in Angular project

Being a French speaker, I apologize in advance for any mistakes I might make. I am also fairly new to Angular, so if you could provide detailed explanations in your responses, it would be greatly appreciated. Thank you. I am trying to import a custom CSS ...

Should I opt for the spread operator [...] or Array.from in Typescript?

After exploring TypeScript, I encountered an issue while creating a shorthand for querySelectorAll() export function selectAll(DOMElement: string, parent = document): Array<HTMLElement> | null { return [...parent.querySelectorAll(DOMElement)]; } ...

Make sure to call the loader function in React Router only when there are path params present

I'm currently implementing the new React Router, utilizing loader functions to fetch data based on the loaded element. My goal is to have certain APIs called regardless of the route, with additional APIs triggered for specific routes. However, I&apos ...

Tips for eliminating validators in dynamic forms within Angular 4

Below is the form group I am working with: this.formData = fb.group({ 'categoryName': [null, Validators.required], 'categoryImage': [null, Validators.required], 'mainCategoryId': [null, Validators.required], 'subCategory ...

Setting up an auto-complete dropdown with PrimeNG and Angular

Struggling with the auto-complete feature, where the dropdown loads initially but fails to filter values as I type. Here's a snippet from service.ts: getUserLocations(UserID: string, allList:string ) { return this._http.get(environment.BASE ...

Error: Cannot modify the constant property 'name' of the function."&squo;

As I attempted to enter text into the input box, an error message appeared after typing my first letter stating "cannot assign to read only property". Below is the code I am referring to: The code of the component can be found here: This is the specifie ...

Exploring Angular: A Guide to Importing Material Components

Trying to incorporate elements such as sliders and tooltips into my project, but encountering issues with imports. I've experimented with adding the import statement for MatSliderModule in various locations like app.module.ts and specific component mo ...

"Utilizing the Power of Typescript with Koa-Router and Passport for a

As a beginner in Typescript, I am facing challenges while trying to integrate koa-router and koa-passport. I have installed all the necessary @types\ packages. import Koa from "koa"; import Route from "koa-router"; import passport from "koa-passport" ...

Create Office Script calculations with quotations included

I am currently attempting to create an Excel office script formula for a cell. Are there any tips on how to insert a formula with quotes into a cell? For example, the following works fine: wsWa.getCell(WaRangeRowCount, 9).setFormula("= 1 + 1"); ...

Type inference error in TypeScript occurs within a conditional statement when the condition relies on the output of a function call rather than a boolean expression

In my TypeScript code, I have a Linked List class that is working perfectly. The class includes a Node type and functions to add items to the list. type ListItem = number | string | object; class Node { private value: ListItem; private next: Node | nu ...

Remove an item from an array within Express using Mongoose

{ "_id": "608c3d353f94ae40aff1dec4", "userId": "608425c08a3f8db8845bee84", "experiences": [ { "designation": "Manager", "_id": "609197056bd0ea09eee94 ...

Using Typescript and webpack to detect variables that are defined in the browser but not in Node environment

My goal is to create a package that can be used on both servers and clients with minimal modifications required. Some libraries are available in Node but not in a browser, while others are accessible in a browser but not in Node. For instance, when utili ...

Fixing Angular minification issue with class names within 5 minutes

Who has encountered the issue of minification affecting class names in Angular 5+ and knows how to resolve it? I have a few classes: class FirstClass { } class SecondClass{ } And a check-function like this: function checkFunction() { const isEqual ...

Encountering a problem while trying to integrate ng-zorro-antd in an Angular 8 project using the CLI command ng add ng-zorro

I am encountering an issue when trying to integrate ng-zorro-antd with Angular 8 using the CLI. I have followed these steps: Create a new project using 'ng new PROJECT_NAME' Navigate into the project directory using 'cd PROJECT_NAME' ...

Automatic Formatting of Typescript in SublimeText

Utilizing Microsoft's Typescript Sublime Plugin, I am able to format a file using the shortcut ^T ^F as outlined in the plugin's feature list. Is there a method to automatically execute this command when saving a file? Similar to the functionali ...

Next.js routing can sometimes be unpredictable, especially when navigating from a nested route

I recently set up a directory named dashboard within the pages folder, and it contains the following files: index.tsx customers.tsx invoice.tsx items.tsx When a user navigates to http://localhost:3000/dashboard, the index.tsx page is displayed. However, ...