I've been working on a project that involves fetching data from the server and manipulating it within the .ts file. However, I seem to be facing a common issue related to Typescript/angular concepts that I'm struggling to grasp...I would really appreciate some assistance with this
user: any;
public doStuff(){
alert(this.user.username);
}
The user object contains various properties, such as 'username', which is initialized in the ngOnInit() block. I am setting it in the ngOnInit method. The service injection is done correctly and the following code works perfectly fine
ngOnInit() {
this.authService.getProfile().subscribe(profile =>{
this.user= profile.user;
this.initStuff();
},
err => {
console.log(err);
return false;
});
}
When I try to call the doStuff() method outside of that code block, it stops functioning and the browser-console shows an error message "cannot read property 'value' of undefined" - why is it showing undefined? Interestingly, when I use {{user.username}} in the component.html, it displays the correct username
ngOnInit() {
this.authService.getProfile().subscribe(profile =>{
this.user= profile.user;
},
err => {
console.log(err);
return false;
});
this.initStuff(); // why can't I call it here? This is where I typically call all my other doStuff() methods
}