我无法将路由参数检索为null。我正在使用angular7。 请在下面找到代码
HeaderComponent ts文件
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();
}
标题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>
应用路由ts文件
const routes: Routes = [
{ path: 'news/:typeId', component: XxxComponent },
{ path: '**', component: XxxComponent }
];
答案 0 :(得分:4)
有两种访问route参数的方法。
您可以在此处获得更多参考:https://angular.io/api/router/ActivatedRouteSnapshot
有关实现,请参见以下代码段
:let id = this.activatedRoute.snapshot.params.typeId; // any param name after "params"
或
this.activatedRoute.params.subscribe((params) => {
let id = params.get('typeId');
});
确保在组件初始化时(即ngOnInit()或之后)使用上面的代码。
答案 1 :(得分:0)
您在(单击)中调用getNewsByCountry,可能cr.value为空,什么是cr.value?是ID吗?
答案 2 :(得分:0)
我试图在“ HeaderComponent ts”中获取该参数,该参数应从“ XxxComponent”中调用。我在XxxComponent ts文件中添加了该路由参数代码,现在可以按预期运行。我可以获取路线参数。
答案 3 :(得分:0)
您也可以尝试
let id = this.activatedRoute.snapshot.queryParams.id
获取所有路由共享的查询参数