ANGULAR params 对象 null 使用 activatedRoute
ANGULAR params object null using activatedRoute
我在尝试获取 :id 参数时遇到问题
这是我的路线:
{
path: 'user',
component: UserComponent,
children: [
{
path: ':id',
component: UserComponent
}
]
},
这是我的组件:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.getUser();
}
getUser() {
this.route.params.subscribe(params => {
console.log(params); // displays empty object
});
}
}
我是不是获取参数有误?
谢谢!
PS欢迎对我的代码提出任何批评或建议!
您正在加载与 Child 相同的组件,这有点奇怪
为此,您的代码应该如下所示
{
path: 'user/:id',
component: UserComponent
}
或
{
path: 'users',
component: UserComponent, // For showing list of users
children: [
{
path: ':id',
component: UserDetailComponent // For Showing detail of specific user
}
]
},
我在尝试获取 :id 参数时遇到问题
这是我的路线:
{
path: 'user',
component: UserComponent,
children: [
{
path: ':id',
component: UserComponent
}
]
},
这是我的组件:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.getUser();
}
getUser() {
this.route.params.subscribe(params => {
console.log(params); // displays empty object
});
}
}
我是不是获取参数有误?
谢谢!
PS欢迎对我的代码提出任何批评或建议!
您正在加载与 Child 相同的组件,这有点奇怪
为此,您的代码应该如下所示
{
path: 'user/:id',
component: UserComponent
}
或
{
path: 'users',
component: UserComponent, // For showing list of users
children: [
{
path: ':id',
component: UserDetailComponent // For Showing detail of specific user
}
]
},