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

The test() function in JavaScript alters the output value

I created a simple form validation, and I encountered an issue where the test() method returns true when called initially and false upon subsequent calls without changing the input value. This pattern repeats with alternating true and false results. The H ...

Struggling to tally the entries and authenticate logins within Ionic 3 and Angular

In my application, users register by providing their email and password, which is then stored in a SQLite database. When the user attempts to log in using the same credentials, they should be redirected to the home page upon successful login. I am facing ...

Dynamic Angular form with nested elements

Need help creating a nested form following the example from angular.io documentation: https://stackblitz.com/angular/pbdkbbnmrdg The objective is to include two DropdownQuestion elements from question.service.ts within a child formgroup called "details", ...

TypeORM ensures that sensitive information, such as passwords, is never returned from the database when retrieving a user

I developed a REST API using NestJs and TypeORM, focusing on my user entity: @Entity('User') export class User extends BaseEntity { @PrimaryGeneratedColumn() public id: number; @Column({ unique: true }) public username: string; publi ...

The error message "Undefined error in Angular 8 when waiting for API call to finish" appears when

if(this.datashare.selectedtableId!=null) { console.log( "inside if condition"); let resp= this.http.get(this.global.apiUrl+"columns/"+this.datashare.selectedtableId); resp.subscribe((data)=>this.users=data); conso ...

Having difficulty generating an Angular 5 Universal server application bundle with @ngtools/webpack

I am currently working on developing a cross-platform app using Angular 5 and WebPack without utilizing the CLI. The main issue I am facing is that I am unable to get the express application to function properly, resulting in encountering the following er ...

The challenges of type verification in Redux reducer

I'm currently facing two specific challenges with Typescript and the Redux reducer. Reducer: const defaultState = { selectedLocation: { id: 0, name: 'No Location' }, allLocations: [{ id: 0, name: 'No Location' }], sele ...

How to limit character input in a Div using Angular 2

I need some guidance on Angular 2 with TypeScript. I want to apply a validation rule to a "Div" element where the maximum length should be set to 100 characters. Additionally, even when text is copied and pasted into the Div, it should not exceed 100 chara ...

Implement mask functionality in Angular Nebular's nbInput for more secure input fields

I am in need of adding masks to input text fields for phone numbers, dates, emails, and more. However, while using Angular and Nebular 5.0.0, I discovered that the official documentation does not provide a mask attribute. I attempted to integrate ngx-mask ...

Title: How to Build a Dynamic Logo Carousel with React and CSS without External Dependencies

Currently, I am in the process of integrating a logo carousel into my React web application using CSS. My goal is to create a slider that loops infinitely, with the last logo seamlessly transitioning to the first logo and continuing this cycle indefinitely ...

Empty initial value for first item in array using React hooks

My goal is to store an array that I retrieve from an API in a useState hook, but the first entry in my array always ends up empty. The initial array looks like this: (3) ["", "5ea5d29230778c1cd47e02dd", "5ea5d2f430778c1cd47e02de"] The actual data I recei ...

When creating utility classes, is it beneficial to offer a non-mutable API to facilitate their integration with frameworks such as React?

Currently, I am working on enhancing the functionality of my DateWithoutTime class. As part of this process, private fields within the class need to be updated by public methods. this.state.dateWithoutTimeInstance.shiftBySpecificDaysCount({ daysCount: 5, ...

Error: Exceeded Maximum Re-Renders. React has set a limit on the number of renders to avoid infinite loops. Issue found in the Toggle Component of Next.js

I am struggling with setting a component to only display when the user wants to edit the content of an entry, and encountering an error mentioned in the title. To achieve this, I have utilized setState to manage a boolean using toggle and setToggle, then ...

summing 3 numbers to a total of 100 percent

I am currently trying to calculate the percentages of different statuses based on 3 count values. Let's assume I have 3 statuses: 1) Passed 2) Failed 3) Skipped When dealing with only two cases, I was able to use a combination of the Floor and Ceil ...

Tips on avoiding issues with the backslash character in Typescript

Can someone help me with creating a regular expression in Typescript that can match the decimal separator character followed by a sequence of zeros in a string? I have tried to come up with an expression as shown below: /\.0+\b/g However, since ...

Switch the following line utilizing a regular expression

Currently, I am facing a challenge with a large file that needs translation for the WordPress LocoTranslate plugin. Specifically, I need to translate the content within the msgstr quotes based on the content in the msgid quotes. An example of this is: #: . ...

What is the importance of having a reference path for compiling an AngularJS 2 project using gulp-typescript?

I wanted to modify the Angular Tour Of Heros project to utilize gulp from this Github Repository. This is the gulpfile.json file I came up with: const gulp = require('gulp'); const del = require('del'); const typescript = require(&apo ...

Ensuring TypeORM constraint validations work seamlessly with MySQL and MariaDB

I recently started using TypeORM and I'm trying to incorporate the check decorator in my MySQL/MariaDB database. However, after doing some research on the documentation and online, it seems that the check decorator is not supported for MySQL. I'v ...

Preventing Redundancy in Angular 2: Tips for Avoiding Duplicate Methods

Is there a way I can streamline my if/else statement to avoid code repetition in my header component? Take a look at the example below: export class HeaderMainComponent { logoAlt = 'We Craft beautiful websites'; // Logo alt and title texts @Vie ...

When launching the Angular SSR app, an uncaught ReferenceError occurs because the document is not defined

After successfully running "npm run dev:ssr" a problem arises when the rendered file shows an error. How can this issue be resolved? ERROR Error: Uncaught (in promise): ReferenceError: document is not defined ReferenceError: document is not defined a ...