6

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 }
    ];
Madhavi
  • 474
  • 2
  • 7
  • 20

4 Answers4

7

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().

Vishnu Singh
  • 431
  • 4
  • 13
1

I am trying to get that Params in "HeaderComponent ts" where it should call from "XxxComponent". I added that route param code in XxxComponent ts file now working as expected. I am able to get the route params.

Madhavi
  • 474
  • 2
  • 7
  • 20
1

You can also try

let id = this.activatedRoute.snapshot.queryParams.id

to get the query parameters shared by all the routes

0

You call getNewsByCountry in (click), probably cr.value is null, what is cr.value? Is the ID?

rikg93
  • 1,101
  • 1
  • 11
  • 21