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 }
];
Since ActivatedRoute can be reused, ActivatedRouteSnapshot is an immutable object representing a particular version of ActivatedRoute . It exposes all the same properties as ActivatedRoute as plain values, while ActivatedRoute exposes them as observables.
The first way is through the route snapshot. The route snapshot provides the initial value of the route parameter map (called the paramMap ). You can access the parameters directly without subscribing or adding observable operators. The paramMap provides methods to handle parameter access like get , getAll , and has .
ActivatedRoutelink. Provides access to information about a route associated with a component that is loaded in an outlet.
There are two ways of accessing a route parameter.
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().
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With