gpt4 book ai didi

angular - 在 angular 7 中获取路由参数为空

转载 作者:行者123 更新时间:2023-12-03 15:49:27 28 4
gpt4 key购买 nike

我无法将路由参数检索为空。我正在使用 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 }
];

最佳答案

有两种访问路由参数的方法。

  • 静态(页面加载一次)
  • 动态(如果在您的应用程序中更改参数而不通过浏览器重新加载页面,则获取更新)

  • 您可以在此处获得更多引用: 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');
    });

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

    关于angular - 在 angular 7 中获取路由参数为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54309003/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com