Is it feasible to record a route with query parameters prior to navigation in Angular?

I am working on rerouting within an application using Angular 2.4 with typescript. The rerouting is triggered by a button click event. Below is the relevant code:

component.html

<button class="btn btn-lg btn-primary" (click)="negotiation()"
                            [disabled]="!negotiationEnable"
                            [hidden]="!hiddenElement">
                        Rerouting Button
</button>

component.ts

negotiation(): void {
        // == Console.log this path with parameters here.. ==
        this.router.navigate(['/simple-search-details'],
            { queryParams: {id: this._negotiation_id, catalogueId: this._negotation_catalogue_id} });
    }

The issue I am facing is that the target URL where the rerouting should lead to is still in development. However, it would be helpful to see how the link appears with the query Parameters and the URL structure.

If I use

console.log(this.router.navigate(...))
to view the command, it results in an Error.

Expected Outcome

/simple-search-details?catalogueId=blah-foo-1bar&id=some-text-id

Answer №1

To detect navigation events in the constructor of a Component, you can add a listener using the following code:

import { Router, NavigationStart } from '@angular/router';

constructor (private _router: Router) {
  _router.events.subscribe(event => {
    if(navigationEvent instanceof NavigationStart) {
      console.log(navigationEvent.url);
    }
  })
}

The NavigationStart event provides information about the route ID and the URL, with parameter values replaced.

For example, if your route is defined as /part/:id, it will output /part/123 when the corresponding route is accessed. This behavior may vary depending on your specific routing configuration.

Answer №2

Utilize a route guard to control navigation, display URLs, and prevent further navigation

import {CanActivate, Router, RouterStateSnapshot, ActivatedRouteSnapshot} from '@angular/router';

@Injectable()
export class AuthGuardService implements CanActivate {

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    alert(state.url);
    return false;
  }

}

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

Problems with the zoom functionality for images on canvas within Angular

Encountering a challenge with zooming in and out of an image displayed on canvas. The goal is to enable users to draw rectangles on the image, which is currently functioning well. However, implementing zoom functionality has presented the following issue: ...

Having trouble installing the gecko driver for running protractor test scripts on Firefox browser

Looking to expand my skills with the "Protractor tool", I've successfully run test scripts in the "Chrome" browser. Now, I'm ready to tackle running tests in "Firefox," but I know I need to install the "gecko driver." Can anyone guide me on how t ...

There seems to be a problem as I am unable to match any routes. Does anyone have any suggestions on how I can resolve this issue?

I am currently developing an Angular recipe application. I have a feature where users can click on the "Full Recipe" button in the saved recipes page to view detailed recipe information. The functionality works perfectly in the recipe item component, but w ...

Transform data into JSON format using the stringify method

I am facing an issue with my TypeScript code where I need to retrieve specific information from a response. Specifically, I want to output the values of internalCompanyCode and timestamp. The Problem: An error is occurring due to an implicit 'any&apo ...

Ways to confirm if the indexed sort is an extension of a string

Suppose I have a function called func with 2 generic arguments const func = <T extends {}, K extends keyof T>() => {}; and a type defined as interface Form { a: boolean; b: string; } then I can call them without encountering any errors func& ...

Losing context when values are passed as typed values

As someone who is still relatively new to typescript, I've been navigating my way through it fairly well so far. However, I recently encountered an issue that has stumped me. My current challenge involves passing data within my React application in t ...

Capture all HTTP requests made by Angular2

I'm trying to find a way to intercept and modify all HTTP requests made by Angular by adding custom headers. In previous releases prior to angular2 RC5, this was achieved by extending the BaseRequestOptions like this: class MyOptions extends BaseRequ ...

Encountering issues with npm install @angular/material for installing angular2 material package

Attempting to install angular2 material using the command npm install @angular/material: [xxx@Latitude-E5550 quickstart]$ npm install @angular/material [email protected] /home/xxx/quickstart └── @angular/[email protected] npm ...

"Encountering a situation where a Typescript function becomes

I am experiencing an issue with the binOp function in my code. The function runs once when called from an expression, but then becomes undefined when called by term. I'm having trouble figuring out why this is happening. I've tried to debug it an ...

Error: The parameter should be a string, not an object

I am having trouble with a function that is supposed to return a string but instead, it returns an object. Unfortunately, I cannot use the .toString() method either. currentEnvironment: string = "beta"; serverURL: string = this.setServerURL(this.currentEnv ...

Unable to utilize ng-Bootstrap datepicker

I recently cloned the quickstart project from the tour of heroes guide on Angular's official website, and I wanted to incorporate the ng-Bootstrap datepicker. However, I encountered some issues with its functionality. Below are the key components of m ...

The Ion-icon fails to appear when it is passed as a prop to a different component

On my Dashboard Page, I have a component called <DashHome /> that I'm rendering. I passed in an array of objects containing icons as props, but for some reason, the icons are not getting rendered on the page. However, when I used console.log() t ...

Exploring Angular 2 Routing with onActivate Functionality

I'm having some trouble setting up a component to use the routerOnActivate hook. I keep encountering an error message stating that the property 'routerOnActivate' is missing in the component called 'SettingsHomeComponent', with the ...

Selecting logic depending on the request body in NestJS

Currently, my controller looks like the following: @Controller("workflow") export class TaskWorkflowController { public constructor( private readonly jobApplicationActivityWorkflow: JobApplicationActivityService ) {} @Post("/:job- ...

What is the best way to bundle a TypeScript package along with its dependencies for seamless integration with various Next.js projects on a local environment

Currently, I am immersed in a project with the following arrangement: / # repository root /core # A local, unpublished npm package used by both projectA and projectB /projectA # A Next.js app /projectB # Another Next.js app In my setup, I gene ...

Trying to assign a value to a key on an object that is supposed to be unchangeable and has been locked in place. [ Angular2 + React Native ]

Currently, I am developing a mobile app using Angular2 + React Native. I encountered an issue when trying to run the following code: <Text [styleSheet]="styles.button" opacityFeedback (tap)="showMore=!showMore" testID="Show_More"> {{showMore ? & ...

How can I efficiently utilize reusable code in Angular 2 to effectively showcase JSON data?

Just starting out with Angular 2 and looking to create reusable code efficiently. Is there a more concise way to write this code? answer1 = false; answer2 = false; answer3 = false; onClick1(){ this.answer1 = true; this.answer2 = false; this.a ...

Error message "Observable_1.Observable.throw is not a function" encountered in Angular Universal RxJs

I encountered an issue on the universal server console log specifically when using SSR (Server-Side Rendering) and not with ng serve. ERROR TypeError: Observable_1.Observable.throw is not a function Below is how my service is configured: import { Inje ...

What are the best practices for incorporating TypeScript into web development projects?

I am currently utilizing express as my server for a straightforward project structured as follows: . ├── src │ └── index.html │ └── index.ts │ └── three.js ├── main.ts ├── package.json └── tsconfig.json ...

What sets typescript apart when using a getter versus a regular function?

Imagine having a class with two methods declared for exclusive use within that class. // 1. private get something() { return 0; } // 2. private getSomething() { return 0; } While I am familiar with getters and setters, I'm intrigued to know if ther ...