Angular 5 ParamMap 不适用于 app.component.ts

标签 angular parameters

我想从路由参数中获取 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/

相关文章:

angularjs - 字符串中的 Angular 2 绑定(bind)表达式(ng2-translate)

angular - 如何从 Angular ActivatedRoute 获取参数

Powershell 无法返回正确的退出代码

android - 如何在程序运行时更改布局参数

angular - 如何从 ng2 子模块中的组件输出()事件?

Angular 6 错误处理 - 如何在模态中显示错误?

css - 如何设置使用 ngx-markdown 呈现的内容的样式?

javascript - jquery mobile传递参数以及div id href

c - 传递数组指针并打印

javascript - 如何将polyfills和外部库与Rollup JS捆绑在一起?