Angular 5 routing is reporting that the queryParams list is currently empty

Having just started with Angular, I've encountered an issue that I can't seem to solve. When passing parameters to the router (using the Router class), the list of parameters on the target site is empty.

let navigationExtras: NavigationExtras ={
  queryParams: {
    uri: item.uri
  }
}

this.router.navigateByUrl('articlelist/article-details', navigationExtras);

In the Article-details component (which uses the ActivatedRoute class):

   ngOnInit(): void {
        console.log("ArticleDetailsComponent " + JSON.stringify(this.route.url));
    this.route.queryParamMap.map(paramMap =>{
            this.uri = paramMap.get('uri');
            console.log(this.uri);
        });
    }

The routing in the ArticleList module (one of the modules in my project) looks like this:

const routes: Routes = [{
  path: '',
  component: ArticleListComponent,
    data: {
      title: 'ArticleList'
    },
  },
{
  path: 'article-details',
  component: ArticleDetailsComponent,
  data: {
    title: 'ArticleDetails'
  },
}
];

Upon logging route.url in the target component, the result appears as follows:

ArticleDetailsComponent {"_isScalar":false,"observers":[],"closed":false,"isStopped":false,"hasError":false,"thrownError":null,"_value":[{"path":"article-details","parameters":{}}]}

If anyone has a solution for this issue, I would greatly appreciate your help :)

Answer №1

If you want to retrieve all query parameters, it's essential to utilize the ActivatedRoute.

Give this a shot -

constructor(
    private activatedRoute: ActivatedRoute
  ) { }

this.activatedRoute.queryParams.subscribe(params => {
      const URI = params['uri'];
    });

Revision

Attempt to pass parameters in this manner -

this.router.navigate(['bloglist/blog-details'], {
      queryParams: {
        uri: post.uri || 'Default'
      }
    });

Answer №2

To specify the parameter in your app's routing module, follow these steps:

{ path: 'customPath/:identifier', component: YourCustomComponent},

Then navigate using:

this.router.navigate(['/customPath/' + identifier]); (using @angular/router/Router)

In your component's constructor, retrieve the parameter like this (using @angular/router/ActivatedRoute):

this.activatedRoute.params.subscribe(params => {
    this.customObject = params['identifier'];
}

Answer №3

If you're looking to avoid relying on Observables, consider taking a snapshot of your route instead. This way, you'll have all the necessary parameters neatly stored in a simple object.

constructor(private router: ActivatedRoute) {}

ngOnInit() {
  console.log(this.router.snapshot.params);
}

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

Revise Swagger UI within toggle button switch

My project aims to showcase three distinct OpenApi definitions within a web application, enabling users to explore different API documentation. The concept involves implementing a toggle button group with three buttons at the top and the Swagger UI display ...

Validation of Angular 5 forms for detecting duplicate words

I need help with a basic form that has one input. My requirement is to validate that the user does not input an existing word. If the user does enter an existing word, I would like to display a message below the input field saying "This word already exis ...

Issue with manipulating element styles using jQuery in Angular2

My method of assigning IDs to elements dynamically using *ngFor looks like this: <div *ngFor="let section of questionsBySubCat" class="col-md-12"> <div class="subcat-container"> <h4 class="sub-cat">{{ section?.subcategory }}& ...

Can you provide any instances of Angular2 projects with intricate routing, specifically with version 2.0.0-rc.1?

Currently, I am in the process of building a web application with angular2 (2.0.0 rc 1) and encountering obstacles due to the insufficient documentation, especially when it comes to establishing intricate routing. Since version 2.0.0 was just released app ...

Ensuring Commitments in the ForEach Cycle (Typescript 2)

Having trouble with promise chains after uploading images to the server in Angular 2 and Typescript. Let's come up with some pseudo-code: uploadImages(images):Promise<any> { return new Promise((resolve, reject) => { for (let imag ...

Tips for showcasing the contents of a file on a website

Greetings! I am a newcomer to the world of web development and I am seeking a method to showcase file content on a webpage. Presently, I have succeeded in loading text file content and displaying it in a large text box. However, I am now interested in di ...

angular overlapping collapsing

Currently, I am developing a chat board application where users can leave comments under each post. I am in the process of creating a button that will collapse all the comments for better visibility, especially as they continue to grow. <div id="collap ...

Modifying the value of a React input component is restricted when the "value" field is utilized

I'm currently utilizing material-UI in my React application. I am facing a challenge where I need to remove the value in an input field by clicking on another component. The issue arises when using the OutlinedInput component with a specified value. ...

Can a substring within a string be customized by changing its color or converting it into a different HTML tag when it is defined as a string property?

Let's discuss a scenario where we have a React component that takes a string as a prop: interface MyProps { myInput: string; } export function MyComponent({ myInput }: MyProps) { ... return ( <div> {myInput} </div> ...

Sharing information between components in Angular 4 and .NET Core applications

I am new to Angular and .NET Core. I have successfully created a web api using .NET Core, which is called from an Angular 4 application. Currently, everything is working smoothly. However, after submitting a form that inserts records into the database, I w ...

Organize JSON data in Angular 6 from an observable based on a specific key

Note: While I am familiar with sorting a regular array of objects using .sort(), I am facing a challenge with an observable object that I am not accustomed to. My task involves retrieving a JSON array of objects with a service: import { Injectable } from ...

Obtain the dimensions (width and height) of a collection of images using Angular and TypeScript

Currently, I am facing an issue with my image upload functionality. My goal is to retrieve the width and height of each image before uploading them. However, I've encountered a problem where my function only provides the dimensions for the first image ...

To use the ModuleWithProviders<T> in the angular-autofocus-fix package, you must provide 1 type argument

Upon successful installation of angular-autofocus-fix I have imported the AutofocusModule However, upon running the Angular project, I encountered the following error: ERROR in node_modules/angular-autofocus-fix/index.d.ts:4:23 - error TS2314: Generic ty ...

On mobile devices, Tailwind CSS prioritizes larger screens over smaller screens when applying styles

Encountering an issue where the custom 2lg:/ lg: screens are conflicting with the md: screen in my React app. Even though the screen is set correctly to md:, it gets overwritten by the custom screens. Refer to the screenshot in "inspect" for a clearer view ...

When trying to reach a particular URL, a 404 error is encountered for a website that is being hosted on

I'm currently experiencing an issue with my angular7/mysql/node.js website hosted on GoDaddy. The problem arises when I try to access specific pages using their URLs instead of the base URL. For example, when I visit www.abcdef.com, the home page loa ...

Is it possible to use static imports with Typescript?

Let's imagine that Object is a module that can be imported and currently we are using Object.getOwnPropertyNames. Is it possible to write the following code instead: import {getOwnPropertyNames} from 'Object'; ...

retrieving dynamic information from beyond the subscribe function

In order to implement canActivate for user routes, I need to first verify the validity of the access token. Below is the approach I am taking: export class AuthGuard implements CanActivate { data:Array<Object>; constructor(private base: BaseServ ...

Learn how to use sanitizer.bypassSecurityTrustStyle to apply styling to Pseudo Elements before and after in a template

Currently, I am attempting to add style to a pseudo element :after <a class="overflow">{{item?.eco}}</a> My goal is to modify the background color of a:after, and I believe this adjustment needs to be made in HTML. I've been thinking ...

Leveraging the Angular (2) routerLinkActive directive to handle dynamic routes

Although my current approach works, I believe there may be a more efficient way to implement this in Angular. The situation is as follows: Imagine nested, inflected paths like /logos and /logo/:id The markup below functions as intended: <li class ...

Error: The term "kendo" has not been defined

While attempting to develop a sample application that loads a kendo-grid wrapped in an angular2 component, I encountered an exception in the Chrome browser as shown below: angular2.dev.js:24821 EXCEPTION: Error in :0:0BrowserDomAdapter.logError @ angular2 ...