我试图在我的 Angular 5 应用程序中获取 URL 参数,我找到了两种方法:
1) 使用paramMap
ngOnInit() {
this.hero$ = this.route.paramMap
.switchMap((params: ParamMap) =>
this.service.getHero(params.get('id')));
}
2) 使用参数
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.id = +params['id'];
});
}
有区别吗?哪一种是最佳做法?
最佳答案
2021 年 9 月更新
以下答案不再正确,Angular team says :
There are no current plans to remove
params
orqueryParams
and there's no benefit to advising against their use.
过时的答案
根据文档:
Two older properties are still available. They are less capable than their replacements, discouraged, and may be deprecated in a future Angular version.
params — An Observable that contains the required and optional parameters specific to the route. Use paramMap instead.
简单高效!
关于Angular 4/5 - 路线 paramMap 与 params,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47809357/