What is the best method for retrieving GET parameters in an Angular2 application?

Is there a way in Angular2 to retrieve GET parameters and store them locally similar to how sessions are handled in PHP?

GET Params URL

I need to obtain the access_token before navigating to the Dashboard component, which makes secure REST Webservice calls that require the token.

@Component({
 selector: 'my-app',
 template: `
 <h1>{{title}}</h1>
  <nav>
    <a [routerLink]="['Dashboard']">Dashboard</a>
    <a [routerLink]="['Heroes']">Heroes</a>
  </nav>
  <router-outlet></router-outlet>
  `,
    directives: [ROUTER_DIRECTIVES],
    providers: [
        ROUTER_PROVIDERS,
        HTTP_PROVIDERS,
        HeroService,
        RouteParams
    ]
})
@RouteConfig([
    {
        path: '/heroes',
        name: 'Heroes',
        component: HeroesComponent
    },
    {
        path: '/dashboard',
        name: 'Dashboard',
        component: DashboardComponent,
        useAsDefault: true
    },
    {
        path: '/getHero/:id',
        name: 'HeroDetail',
        component: HeroDetailComponent
    },
])
export class AppComponent {
    title = 'Tour of Heroes';
    private token2;

    constructor(
        private _routeParams:RouteParams) {

        this.token2 = _routeParams.get('access_token');
        console.log("token from Url : "+ this.token2);
    }
}

Upon launching the app, an "EXCEPTION: Cannot resolve all parameters for 'RouteParams'(?)" error is encountered.

hero.service.ts :

@Injectable()
export class HeroService {
    ot: Observable<string>;
private token2 =  'test';

private serviceUrl = 'http://localhost:8080/Context_Path/';
private token = "xXXXX";
private headers = new Headers();

constructor(private http:Http){
    this.headers.append('Authorization', 'bearer '+ this.token);
    this.headers.append('Content-Type', 'application/json');
}

// More code here...

Dashborad.component.ts :

import { Component, OnInit } from 'angular2/core';
import { Hero } from './hero';
import { HeroService } from './hero.service';
import { Router } from 'angular2/router';

// More code here...

Errors persist even after attempting relevant edits. Troubleshooting continues to resolve issues related to 'RouteParams'.

Answer №1

Updating Deprecated Router Method

To address the deprecated router method, include these providers either in the bootstrap() function or solely within the AppComponent.

bootstrap(AppComponent, [
    ROUTER_PROVIDERS,
    HTTP_PROVIDERS])

Remove these providers from all other locations to avoid redundant declarations throughout the application. It is unnecessary to provide the same providers multiple times if they are intended to be shared globally.

Additionally, ensure that when using RouteParams and ROUTER_PROVIDERS, you import them specifically from angular2/router rather than angular2/core.

For further information, refer to my response on How to Retrieve GET Parameters in Angular2?

In the root component, it is possible to inject the router, subscribe to route events, and retrieve parameters from the router as follows:

export class AppComponent {
  constructor(private router:Router) {
    router.subscribe(route => {
      console.debug(this.router.currentInstruction.component.params);
    });
  }
}

On components added by the router, one can inject RouteParams and access the values like so:

export class Other{
    constructor(private routeParams: RouteParams) {
    console.debug(this.routeParams);
    console.log(this.routeParams.get('filter_industry'));
    console.log(this.routeParams.get('filter_start_with'));
  }
}

For a detailed example, view this Plunker demonstration

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

Constructor not executing when using Object.create

Attempting to instantiate a class within a static method, I am using Object.create(this.prototype), which appears to be functioning correctly. Nonetheless, when I check the console, my property items is showing as undefined. The base class called model lo ...

Version discrepancy in module metadata

Yesterday everything was running smoothly with Angular 2 and Angular Material, but today I encountered an error when trying to run the program. Can someone please help? ERROR in Error: Metadata version mismatch for module E:/Demo/crud/ node_modules/ ...

Setting up the Font Awesome Pro version in Angular using the Font-Awesome package

The process of installing the pro version of Angular Font-awesome began with setting up my registry using these commands: npm config set "@fortawesome:registry" https://npm.fontawesome.com/ && \ npm config set "//npm.fontawesome.com/:_authTo ...

Ways to access a property within an object using TypeScript

Can you help me extract the "attributes" array from this object and store it in a new variable? obj = { "_id": "5bf7e1be80c05307d06423c2", "agentId": "awais", "attributes": [ // that array. { "created ...

Tips for managing the outcome of an HTTP Post request

I am currently working with Angular 2 and Node.js, attempting to incorporate braintree into my project, which has proven to be quite challenging. My current approach involves utilizing an HTTP Post request to send back the result object from the transacti ...

What are some ways to incorporate advanced/nested type variables when using arrow functions?

Is there a way to use "advanced/nested" type variables, similar to how T is utilized in this function declaration, when working with arrow functions? function wrapInObject<T>(key: string) { return (x: T) => ({ [key]: x }); } I attempted to ach ...

What is the best way to determine the remaining time until a cookie expires in seconds?

I recently set a cookie with an expiration time of 2 minutes. Now, I am looking for a way to display a countdown in HTML showing the seconds remaining before that specific cookie expires using Angular 2. ...

What causes the discrepancy in errors when dealing with subtype versus regular assignments?

Below is a sample code that has been checked by TypeScript playground https://www.typescriptlang.org/play/ interface PartialCustomData { option?: number; } interface A { [key: string]: string | PartialCustomData; } interface B extends A { [k ...

The functionality of Angular 2 md-radio buttons in reactive forms seems to be hindering the display of md-inputs

Currently, I am following the instructions for implementing reactive form radio buttons on a project using Angular 2.1.2 and Google's MD-alpha.10 Atom-typescript shows no errors in my code. However, when testing the application, I encountered the foll ...

Can TypeScript modules be designed to function in this way?

Seeking to create a versatile function / module / class that can be called in various ways: const myvar = MyModule('a parameter').methodA().methodB().methodC(); //and also this option should work const myvar = MyModule('a parameter') ...

The dropdown in the Model Driven Form is malfunctioning and failing to provide the expected value

My form validation using FormBuilder is working well, except for the dropdowns. The value selected in the dropdown option is not updating in the component class. Only the input boxes trigger the event, but not the dropdowns. this.form = formBuilder.group( ...

The application rejected the application of styles from 'http://localhost:1234/node_modules/primeicons/primeicons.css' as the MIME type (text/html) was not compatible

Encountering an error when attempting to add the following styles in index.html within my Angular 6 application. Getting a refusal to apply the style from 'http://localhost:1234/node_modules/primeicons/primeicons.css' because its MIME type ...

Receiving a reply from the axios function

Whenever I try to call the lookUpItem function from ItemSearch.vue, I always get an undefined response. Code snippet from ItemSearch.vue: <script setup lang="ts"> import { lookUpItem } from '../systemApi' async fu ...

The functionality of router.navigate in Angular 5 seems to be malfunctioning

I am struggling with redirecting a user to another page based on a certain condition. Here is an example of my login component: ngOnInit() { console.log(">>> router", this.router) console.log(">>> activatedRoute", this.activate ...

Tips for verifying the Reactive formControl/formArray when submitting

In my scenario, I am working with a FormGroup titled Parent, which includes a FormArray as a control. This FormArray consists of another FormGroup referred to as the Child. Main Goal The main objective here is to perform validation on all controls of a sp ...

What is the best way to manage the connections in my D3 tree chart?

I've been working on customizing a tool from an open source library called angular-d3-tree, but I'm struggling with getting the links to connect properly in my D3 tree structure. This is what my current tree layout looks like: https://i.stack.im ...

When converting a .ts file to a .js file using the webpack command, lengthy comments are automatically appended at the end of

As a backend developer, I recently delved into UI technologies and experimented with converting TypeScript files (.ts) to JavaScript files (.js) using the webpack command. While the conversion works well, the generated .js file includes lengthy comments at ...

Using TypeScript's type casting functionality, you can easily map an enum list from C#

This is a C# enum list class that I have created: namespace MyProject.MyName { public enum MyNameList { [Description("NameOne")] NameOne, [Description("NameTwo")] NameTwo, [Description("NameThree")] NameThree ...

Implementing Lazy Loading in Angular 7 with deeper nested children components

I might have some difficulty explaining the issue, but I have a StackBlitz example to demonstrate. Check out this StackBlitz example Take note of the Lazyloading 'users'... app.routes.ts //import { NgModule } from '@angular/core'; i ...

Navigating the proper utilization of exports and subpaths in package.json with TypeScript

As a newbie in creating npm packages using TypeScript, I've encountered some issues that I believe stem from misinterpreting the documentation. Currently, I am working with Node 16.16.0 and npm 8.13.2. Here is the structure of my project: src/ ├─ ...