Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 5 ParamMap在app.component.ts上不工作_Angular_Parameters - Fatal编程技术网

Angular 5 ParamMap在app.component.ts上不工作

Angular 5 ParamMap在app.component.ts上不工作,angular,parameters,Angular,Parameters,我想从路由参数中获取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.componen

我想从路由参数中获取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上编写代码的目的是因为我在app.component上使用的是navbar,所以当用户连接时,预期的结果是从route获取id,这样navbar将显示“Welcome user1”。有解决办法吗

您可以从
AccountComponent
中选择
idC
,并将值分配给服务内部的属性

帐户.组件.ts

constructor(private route: ActivatedRoute, myService: MyService) { }

ngOnInit(){  
  const id = this.route.snapshot.paramMap.get('idC');
  this.myService.id = id;
  console.log(id);
}
constructor(private route: ActivatedRoute, myService: MyService) { }
AppComponent
访问相同的服务,并在HTML中使用该变量

例如,在您的app.component.ts中

constructor(private route: ActivatedRoute, myService: MyService) { }

ngOnInit(){  
  const id = this.route.snapshot.paramMap.get('idC');
  this.myService.id = id;
  console.log(id);
}
constructor(private route: ActivatedRoute, myService: MyService) { }
以及你的app.component.html

<p>ID: {{myService.id}}</p>
ID:{{myService.ID}


您也可以在不使用服务的情况下获得参数值

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);
    });
  });

}

您是否尝试订阅
路由。paramMap
可观察以侦听更改?您能给我一个订阅的示例吗?@KrishnaRathore在下面的回答中已经这样做了:在myservice上安装什么?@Atom-这是一个可用于组件之间通信的服务。它可能是一个空服务,可能称为
共享数据.service.ts
。在两个组件中注入相同的服务,并以上面HTML中使用的方式使用它。是的,我知道,但如何将id值从AccountComponent分配给服务?你能给我一个我的服务的样品吗。感谢you@Atom-使用命令
ng g service my service
创建一个服务,可能是一个空服务。然后将上面提到的
account.component.ts
代码写在
account.component.ts
内的答案中。然后在你的
app.component.ts
中注入相同的服务,并在上面提到的HTML中访问它。非常感谢,成功了!