I have a component that renders data retrieved from the backend. Before rendering the data needs to be filtered down based on a parameter. The last segment of the URL is a filter value, how do I pass it down into the component?
First of all, if you provide us with a code example will be easier.
Now, in your app.routes.ts you should have something like this:
{
path: 'detail/:id',
component: HeroDetailComponent
}
Now you will be able tou navigate to detail/11 in this case.
In detail component you need to import this:
import { ActivatedRoute } from '@angular/router';
and add it to the constructor as private:
private route: ActivatedRoute
Then you can get the id param like this:
this.route.params.subscribe(params => {
let id = +params['id'];
this.heroService.getHero(id)
.then(hero => this.hero = hero);
});
In this case the hero id is a number. Route parameters are always strings. So we convert the route parameter value to a number with the JavaScript (+) operator. Keep that in mind.
As mentioned here , it will be better if you implements ngOnInit (subscribe to the params observable) and ngOnDestroy (destroy the sub)
you can use route params in the constructor of your component
https://angular.io/guide/router
https://angular.io/api/router/Params
constructor(routeParams: RouteParams) {
this.filter = routeParams.get('custom_filter');
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.