I am puzzled by the error thrown in the code below:
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 {
user: {id: number, name: string};
constructor(private route: ActivatedRoute) {}
ngOnInit()
{
this.user.id = this.route.snapshot.params['id'];
this.user.name = this.route.snapshot.params['name'];
console.log(this.user.id);
console.log(this.user.name);
}
}
ERROR TypeError: this.user is undefined
However, when I modify the code as shown below, the error does not occur:
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 {
user: {id: number, name: string};
constructor(private route: ActivatedRoute) {}
ngOnInit()
{
this.user = {
id: this.route.snapshot.params['id'],
name: this.route.snapshot.params['name']
}
console.log(this.user.id);
console.log(this.user.name);
}
}
I am struggling to comprehend why one version executes without errors while the other does not.
I wonder if my understanding of user being a JSON object is correct. If so, why am I unable to access it with this.user.id?
Any insights would be appreciated.