[英]Angular 5 ParamMap not working on app.component.ts
I want to get id from route params but it return null as value. 我想从路由参数获取id,但它返回null作为值。
app.component.ts: 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);
}
routing.ts: routing.ts:
{ path: 'profile/:idC', component: AccountComponent }
The aim of code on app.component is because I'm using navbar on app so when a user is connected, the expected result is to get id from route so that navbar will display "Welcome user1". app.component上的代码的目的是因为我在应用程序上使用导航栏,所以当用户连接时,预期的结果是从路由获取id,以便导航栏将显示“Welcome user1”。 Any solution ?
有解决方案吗
You can also get params value without 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);
});
});
}
You can pick idC
from your AccountComponent
and assign the value to a property inside service. 您可以从
AccountComponent
选择idC
,并将值分配给服务中的属性。
account.component.ts account.component.ts
constructor(private route: ActivatedRoute, myService: MyService) { }
ngOnInit(){
const id = this.route.snapshot.paramMap.get('idC');
this.myService.id = id;
console.log(id);
}
Access the same service from your AppComponent
and use that variable inside your HTML. 从
AppComponent
访问相同的服务,并在HTML中使用该变量。
For example, inside your app.component.ts 例如,在app.component.ts中
constructor(private route: ActivatedRoute, myService: MyService) { }
and your app.component.html 和你的app.component.html
<p>ID: {{myService.id}}</p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.