angular2 routing - Angular 2/4 How to get route parameters in app component? -
as new angular 2/4 having trouble setting new application per need.
i trying build application called application. calling application send parameter token, username, application id , etc.
now, in angular 2/4, app.component our landing component , every first request go through it. so, want parameter here in app component , load user detail, make local session , move other stuff.
problem when trying access these parameter getting anything.
here url start angular application: http://localhost:86/dashboard?username=admin&token=xyz&appid=8
here routing file code:
const routes: routes = [ { path: 'dashboard/:username, token', component: appcomponent } ]; @ngmodule({ imports: [routermodule.forroot(routes)], exports: [routermodule] }) export class approutingmodule { }
here app component code:
import { component, oninit } '@angular/core'; import { authenticationservice } 'app/services/authentication/authentication.service'; import { user } 'app/models/user/user'; import { appconfig } 'app/helpers/appconfig'; import { activatedroute, router } '@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 params empty don't know why?
thanks in advance!
as in image params object has nothing.
change route this
const routes: routes = [ { path: 'dashboard/:username', component: appcomponent } ];
component
import {router, activatedroute, params} '@angular/router'; import {oninit, component} '@angular/core'; import {subscription} 'rxjs/subscription'; @component({...}) export class mycomponent implements oninit { subscription:subscription; constructor(private activatedroute: activatedroute) {} ngoninit() { // subscribe router event this.subscription = this.activatedroute.queryparams.subscribe((params: params) => { let userid = params['username']; let token = params['token']; console.log(userid); }); } ngondestroy() { // prevent memory leak when component destroyed this.subscription.unsubscribe(); } }
Comments
Post a Comment