Angular router navigation with query parameters example

Project: bookmarks.dev

Use the queryParams extra parameter of the router navigate method:

  constructor(private router: Router,
              private httpClient: HttpClient) {
    this.publicSnippetsApiBaseUrl = environment.API_URL + '/public/snippets';
  }

  getPublicSnippetById(snippetId: string): Observable<Codelet> {
    return this.httpClient
      .get<Codelet>(`${this.publicSnippetsApiBaseUrl}/${snippetId}`).pipe(
        catchError(() => {
          this.router.navigate(['/404-snippet'],
            {
              queryParams: {snippetId: snippetId}
            });
          return throwError('Error 404');
        }));
  }

On the receiving side you can extract the parameter from the ActivatedRoute’s queryParamMap property

import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  template: '  <div id="about-content" class="jumbotron"><h5>Snippet with the id "" was not found - the submitter might have deleted it</h5> </div>'
})
export class SnippetNotFoundComponent {
  snippetId: string;

  constructor(private route: ActivatedRoute) {
    this.snippetId = this.route.snapshot.queryParamMap.get('snippetId');
  }
}

Reference - https://angular.io/guide/router#activated-route


Shared with from Bookmarks.dev. Use the Copy to mine functionality to copy this snippet to your own personal collection and easy manage your code snippets.

Subscribe to our newsletter for more code resources and news

Adrian Matei

Adrian Matei
Life force expressing itself as a coding capable human being

Mongo create full text index example

Code snippets showing how to create a mongo create full text index and how to search for results with its help. Continue reading

Mongo full text search example

Published on February 07, 2021

Mongoose query pagination example

Published on February 05, 2021