我想从路由参数中获取 id,但它返回 null 作为值。
应用程序组件.ts:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
constructor(private route: ActivatedRoute) { }
ngOnInit(){
const id = this.route.snapshot.paramMap.get('idC');
console.log(id);
}
路由.ts:
{ path: 'profile/:idC', component: AccountComponent }
app.component 上代码的目的是因为我在应用程序上使用导航栏,所以当用户连接时,预期结果是从路由获取 id,以便导航栏显示“欢迎用户 1”。任何解决方案?
最佳答案
也可以在没有service的情况下获取params值
constructor(private router: Router, private route: ActivatedRoute) {}
ngOnInit() {
this.router.events.subscribe((event: any) => {
let r = this.route;
while (r.firstChild) {
r = r.firstChild
}
r.params.subscribe(params => {
console.log(params.idC);
});
});
}
关于Angular 5 ParamMap 不适用于 app.component.ts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52035462/