angular - Angular 5 ParamMap 不适用于 app.component.ts
问题描述
我想从路由参数中获取 id,但它返回 null 作为值。
app.component.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”。有什么解决办法吗?
解决方案
您也可以在没有服务的情况下获得参数值
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);
});
});
}