Getting route param as null in angular 7

Madhavi picture Madhavi · Jan 22, 2019 · Viewed 10.7k times · Source

I am unable to retrive the route param as null. I am using angular7. Please find the code below

HeaderComponent ts file

    import {Router, ActivatedRoute} from '@angular/router';
    constructor(private httpService: HttpClient, private router: Router, private activatedRoute: ActivatedRoute) {
             this.getNewsSelectedFromRouteParam();
        }
    getNewsSelectedFromRouteParam() {
            alert();
            let id = this.activatedRoute.snapshot.paramMap.get('typeId');
            alert(id);
        }
getNewsByCountry(newsTypeSelected: any) {
        this.router.navigate(['/news',newsTypeSelected]);
        this.getNewsSelectedFromRouteParam();
    }

Header html

<div class=" dropdown-toggle" data-toggle="dropdown">
                XXX
            </div>
            <div class="dropdown-menu">
                <div *ngFor="let cr of country" class="dropdown-item"
                    (click)="getNewsByCountry(cr.value)" >{{cr.name}}</div>
            </div>

app routing ts file

 const routes: Routes = [
        { path: 'news/:typeId', component: XxxComponent },
    { path: '**', component: XxxComponent }
    ];

Answer

Vishnu Singh picture Vishnu Singh · Jan 22, 2019

There are two ways of accessing a route parameter.

  1. Statically (One time when page loaded)
  2. Dynamically (Gets updated if param is changed within your app without reloading page by browser)

You can get more reference here: https://angular.io/api/router/ActivatedRouteSnapshot

See following snippet for implementation:

let id = this.activatedRoute.snapshot.params.typeId; // any param name after "params"

or

this.activatedRoute.params.subscribe((params) => {
    let id = params.get('typeId');
});

Make sure you are using above code when component is initialized i.e. in or after ngOnInit().