Angular 2/4 How to get route parameters in an application component?

enter image description here Since I'm new to angular 2/4, I am having trouble setting up a new application to suit my needs.

I am trying to create an application that will be called from another application. The calling application will send some parameter, for example, token, username, application identifier, etc.

Now, as in angular 2/4, app.component is our landing component, and every first request will go through it. So, I want to get this parameter here in the application component and load some user details, make a local session and go to another material.

Problem

is that when I try to access these parameters, I get something.

Here is the URL that my angular application will launch: http: // localhost: 86 / dashboard? Username = admin & token = xyz & appId = 8

Here is my routing file code:

const routes: Routes = [ { path: 'dashboard/:username, token', component: AppComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } 

Here is my application component code:

 import { Component, OnInit } from '@angular/core'; import { AuthenticationService } from 'app/services/authentication/authentication.service'; import { User } from 'app/models/user/user'; import { AppConfig } from 'app/helpers/AppConfig'; import { ActivatedRoute, Router } from '@angular/router'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { _user: User = new User(); obj: any; error: any; loginName: string; private id: any; constructor( private authenticationService: AuthenticationService, private config: AppConfig, private route: ActivatedRoute, private router: Router ) { } ngOnInit() { this.loadCurrentUserDetail(); this.getParamValues() } getParamValues() { this.id = this.route.queryParams.subscribe(params => { this.loginName = params['username']; }); } 

Here the parameters are empty, I don’t know why?

Thanks in advance!

As with the params object of the image, there is nothing.

+5
source share
2 answers

This issue has been resolved after posting. here

I needed to create a separate Root component, and I saved my Router-Outlet and added this component as my boot module, and it will work! I have no reputation for more than 50, if I had, than I would thank him in the same post. Thanks man @Fabio Antunes

+3
source

This is your way in angular 5:

 import { Router , ActivatedRoute } from '@angular/router'; constructor(private activeRoute: ActivatedRoute){} ngOnInit() { console.log(this.activeRoute.snapshot.params['username']); } 
-1
source

Source: https://habr.com/ru/post/1270199/


All Articles