25

enter image description hereAs I am new to angular 2/4 I am having trouble setting up a new application as per my need.

I am trying to build an application which will be called for from some another application. Calling application will send some parameter like token, username, application id and 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 those parameter here in app component and load some user detail, make a local session and the move to other stuff.

problem is when I am trying to access these parameter I am getting anything.

Here is the URL which will start my angular application: 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 App 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 params is empty don't know why?

Thanks in advance!

As in image params object has nothing.

0

5 Answers 5

29

For one time value use like below:

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

constructor(private route: ActivatedRoute){}
ngOnInit() {
    console.log(this.route.snapshot.params['username']);
}

The above snapshot method. Snapshot method just gives you result once you initiate the component. So this will keep on working if you change the route or destroy the component and initiate again only.

A solution for the downvoters and/or anyone who want to update the param each time the route change will be:

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

constructor(private route: ActivatedRoute){}
ngOnInit() {
    // Works first time only
    console.log(this.route.snapshot.params['username']);
    // For later use, updates everytime you change route
    this.route.params.subscribe((params) => {console.log(params['username'])});
}
Sign up to request clarification or add additional context in comments.

6 Comments

Why is this answer downvoted? It's a clean good working solution in the current Angular version (6).
People have their reasons to hate even the best moreover it's just another answer
Good solution. I use an alternative version to fetch the values on ngOnInit using 'this.route.params' directly, without the 'snapshot'. Anyone knows what's the difference?
the downvote is because the question is for the app component. the app component is non-routed and will therefore not be able to get params via activated route.
but it will be empty, the first time i open the application, which takes us to the original problem how to solve the "empty param"-problem. The app.component.ts is not routed, and knows therefore nothing about the used params. If i have a route like :username/:token/:whatever it will not be able to to map param.username, param.token or param.whatever
|
8

This post solved problem. here

I needed to create a separate component Root and in that i kept my Router-Outlet and added this component as my bootstrap module and it worked!! I do not have reputation more than 50 if i had than i would thanked him on the same post. Thanks man @Fabio Antunes

Comments

1
import { Component, OnInit, OnDestroy } from '@angular/core';
import {  Router, ActivatedRoute, Params, RoutesRecognized  } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  constructor( private route: ActivatedRoute, private router: Router ) {}

  ngOnInit(): void {
    this.router.events.subscribe(val => {
       if (val instanceof RoutesRecognized) {
         if (val.state.root.firstChild.params.id) {
          localStorage.setItem('key1', val.state.root.firstChild.params.id);
          localStorage.setItem('key2', val.state.root.firstChild.params.id2);
         }
            console.log('test', val.state.root.firstChild.params);
        }
    });

}

}

Comments

0

My application had the need to read queryParams in appComponent (not-routed) to be able to set some variables before routing to any other component. I didn't want to change the architecture to route appComponent.

This is the approach I took by subscribing to router events:

private _queryParamsSet: boolean = false;
  constructor(
    private _router: Router,
    private _activatedRoute: ActivatedRoute
  ) { }

  async ngOnInit() {    
     const onNavigationEnd = this._router.events
      .pipe(
        tap((data) => {
          if (!this._queryParamsSet && (data as NavigationStart)?.url) {
            const queryParams = CoreHelper.getQueryParamsFromURL((data as 
               NavigationStart).url);
            if (queryParams) {
              // set variables which will eventually decide which route to take
            }
            this._queryParamsSet = true;
          }
        }),
        filter(
          event => event instanceof NavigationEnd
        ));
}

Comments

0

The method that works for me is a combination of ActivatedRoute and Router.

ngOnInit(): void {
    this.router.events
      .pipe(
        filter(event => event instanceof NavigationEnd), // Wait for navigation to finish
        map(() => this.activatedRoute),                 // Start with the root route
        map(route => {
          while (route.firstChild) {
            route = route.firstChild;                   // Navigate to the deepest child route
          }
          return route;
        }),
        mergeMap(route => route.params)                 // Access route parameters
      )
      .subscribe(params => {
        this.routeParams = params;
        console.log('Global Route Params:', params);
      });
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.