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

Distinguishing between web development, frontend, and backend: Identifying ownership of an entity by a user

In my web application, I have a setup where each user can have multiple projects and each project can have multiple users. This relationship is managed through three tables in the database: user, project, and user2project which maps the n:m relation betwee ...

Implementing lazy loading in a different ng-module: Step-by-step guide

I currently have two ng-modules set up Dash Board Repeat order list I loaded the Repeat order module through lazy loading. Now I am trying to integrate the Repeat order module inside the dashboard as HTML content <app-repeatorderlist></app-re ...

Encountering an issue with Angular 2.0.1 Router where it throws an EmptyError due to

I am struggling to set up Angular 2 routing properly. I am currently using Angular 2 with Webpack. While looking at the Angular 2 webpack starter, I noticed they had webpack handling their html and links generation, but I was hoping to avoid webpacking my ...

Setting up angular-cli project for rc5- Step by step guide

Trying to integrate angular-cli with angular 2 rc5 but facing challenges: The issue of 'Promise' not being found After attempting to install 'npm install -g angular-cli@webpack', typings did not get installed, resulting in WebStorm un ...

conflict between ng-content and textarea elements

My custom component called my-textarea has a unique template structure: <textarea> <ng-content></ng-content> </textarea> However, when I try to input text into the component using the same method as a regular textarea HTML eleme ...

Get rid of any vacant spaces in -translate-y by utilizing Tailwind CSS

I am experiencing an issue with some empty space in my profile container that I would like to have removed. The profile container is where the problem lies. <div className='h-auto w-[650px] z-10 rounded-xl' style={{ backdropFilter: `blur(4 ...

Encountering an error where `ng serve` is failing because it cannot locate the local workspace file (`angular.json`) for angular 5

Ensuring I'm in the correct directory. After successfully running `ng serve` earlier today, I am now encountering errors: Local workspace file ('angular.json') could not be found. Error: Local workspace file ('angular.json') coul ...

Issue: formGroup function requires a valid instance of FormGroup. Kindly ensure you are passing the correct parameter. Encountering the error even

I've seen this question asked countless times, but it seems like most of the solutions are related to typos. I have simplified my code to match exactly what the error message is suggesting: Here is the relevant part of my HTML: <div [formGroup]=" ...

Combining subclasses in TypeScript

Do you need help with a tricky situation? ...

Arrange my Firebase Angular users based on a specific value, encountering an error stating "sort is not a function

I'm working on an application using Firebase and Angular, and I have a database containing information about my users: My goal is to sort the users based on their "ptsTotal". In my users.service file, I have a function called getUsersByPoints. Howev ...

Tips for accessing data from a local JSON file in your React JS + Typescript application

I'm currently attempting to read a local JSON file within a ReactJS + Typescript office add-in app. To achieve this, I created a typings.d.ts file in the src directory with the following content. declare module "*.json" { const value: any; ex ...

Avoid flickering of images by properly handling the object URL when setting the image source in an asynchronous pipe

Implementing a JWT authorized endpoint for images has made it impossible to directly link to image urls in HTML. To work around this issue, we have created an async pipe that loads the image with proper authorization (handled by an HTTP interceptor, not s ...

Routing in Angular 2 with .NET Core

I am experiencing an issue with my ASP.NET CORE app that utilizes angular2 routing. When I run the app locally, the routes work as expected. However, once I publish it to the server (running IIS 7), the routes seem to resolve to the server root instead of ...

Dealing with Angular CORS Problems While Sending Successive Requests

I am currently working with Angular 6 and my backend consists of a node API. Occasionally, I encounter a CORS issue while making HTTP GET requests every 5 seconds. const url = 'https://<removed>.com/api/v1/transactions/' + transactionI ...

Avoid using unnecessary generic types while updating a TypeScript interface on DefinitelyTyped, especially when using DTSLint

After attempting to utilize a specific library (query-string), I realized that the 'parse' function was returning an any type. To address this, I decided to update the type definitions to include a generic. As a result, I forked the DefinitelyTy ...

Objects vanish 10 seconds after appearing [Angular2, *ngFor]

My Angular2 template is quite straightforward: <span *ngFor="let item of items"> {{ item.description }} </span> Here is the TypeScript logic for it: let list = new Map(); for(let j = 0; j < 100; j++) { list.set(j, { description: j.toS ...

What is the process for exporting the reducer function and integrating it into the storeModule.forRoot within an Angular application?

Recently, I started delving into ngrx and decided to educate myself by going through the official documentation on their website ngrx.io. During this exploration, I came across a puzzling piece of code in one of their reducers. The file in question is cou ...

Prevent TypeScript from generalizing string literals as types

I have a constant Object called STUDY_TAGS with specific properties const STUDY_TAGS ={ InstanceAvailability: { tag: "00080056", type: "optional", vr: "string" }, ModalitiesinStudy: { tag: "00080061", type: " ...

What is the best way to access data from a local JSON file in Gatsby when using TypeScript and GraphQL?

I'm updating my former gatsby site using TypeScript. I encountered an issue while trying to retrieve data from a local JSON file: There appears to be an error in your GraphQL query: Cannot find field "allNavigationLinksJson" on type "Q ...

Angular does not support the functionality of having multiple material paginations within a single component

I am currently working on creating a component that contains two dataTables, each with a different dataSource. However, I am facing an issue where my Tables are not visible immediately after the component is loaded due to the *ngIf directive being used. Be ...