Mad*_*avi 6 angular-routing routeparams angular angular7
我无法将路由参数检索为空。我正在使用 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();
}
Run Code Online (Sandbox Code Playgroud)
标题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>
Run Code Online (Sandbox Code Playgroud)
应用路由ts文件
const routes: Routes = [
{ path: 'news/:typeId', component: XxxComponent },
{ path: '**', component: XxxComponent }
];
Run Code Online (Sandbox Code Playgroud)
有两种访问路由参数的方法。
您可以在此处获得更多参考:https : //angular.io/api/router/ActivatedRouteSnapshot
请参阅以下代码段以了解实现:
let id = this.activatedRoute.snapshot.params.typeId; // any param name after "params"
Run Code Online (Sandbox Code Playgroud)
或者
this.activatedRoute.params.subscribe((params) => {
let id = params.get('typeId');
});
Run Code Online (Sandbox Code Playgroud)
确保在组件初始化时使用上述代码,即在 ngOnInit() 中或之后。
我试图在“HeaderComponent ts”中获取应该从“XxxComponent”调用的参数。我在 XxxComponent ts 文件中添加了该路由参数代码,现在可以按预期工作。我能够获取路线参数。
| 归档时间: |
|
| 查看次数: |
10308 次 |
| 最近记录: |