Angular 角度2+;从激活的路由参数分配数据

Angular 角度2+;从激活的路由参数分配数据,angular,angular-routing,Angular,Angular Routing,这是代码。我试图将一些数据分配给用户对象。然后我尝试通过方法1将数据分配给它: export class UserComponent implements OnInit { user: {id: number, name: string}; constructor(private route: ActivatedRoute) { } ngOnInit() { // this.user = { // id: this.route.snapshot.params.

这是代码。我试图将一些数据分配给用户对象。然后我尝试通过方法1将数据分配给它:

export class UserComponent implements OnInit {
  user: {id: number, name: string};

  constructor(private route: ActivatedRoute) { }

  ngOnInit() {
    // this.user = {
    //   id: this.route.snapshot.params.id,
    //   name: this.route.snapshot.params.name
    // }
    this.user.id = this.route.snapshot.params.id;
    this.user.name = this.route.snapshot.params.name;
  }

}
实际上,它并不起作用。但后来我尝试了另一种方法-2,它看起来与方法-1非常相似,而且效果很好。我想知道这两种方法的区别是什么

// method-1
    this.user.id = this.route.snapshot.params.id;
    this.user.name = this.route.snapshot.params.name;

对于方法1,您使用的声明是错误的。 因为这将创建用户对象的蓝图,这样就不可能使用方法1在对象中存储数据

以下是解决方案:

   // method-2
     this.user = {
       id: this.route.snapshot.params.id,
       name: this.route.snapshot.params.name
     }
如果以这种方式定义用户对象,那么方法1和方法2都可以正常工作

user:any = {id: '', name: ''};