我正在使用angular,我的ngOnInit订阅数据并将其设置为我的用户名属性。我不明白的是当我在console.log(this.username)时,我将根据我对控制台日志定位的代码行进行未定义,我不明白为什么会这样做。
export class DashboardComponent implements OnInit {
username: string;
ngOnInit() {
this.authService.getProfile().subscribe(profile => {
this.username = profile.user.username;
console.log(this.username); <============== works here
},
err => {
console.log(err);
return false;
});
this.getLists();
console.log(this.username); <=========== get undefined here
}
getLists(): void {
console.log(this.username); <=========== get undefined here (need it to work here)
}
addList(newItem): void {
console.log(this.username); <=========== works here
}
我的addList函数链接到(onClick)事件,控制台日志在这里工作,直接在我的订阅函数中。但是,当我试图在我的getList函数或我的ngOnInit的最后一行控制台登录时,我得到了未定义,我不明白它为什么这样做?我错过了什么?
答案 0 :(得分:0)
你没有在async中使用它
export class DashboardComponent implements OnInit {
username: string;
ngOnInit() {
this.authService.getProfile().subscribe(profile => {
this.username = profile.user.username;
this.getLists();
},
err => {
console.log(err);
return false;
});
}
getLists(): void {
// this function gonna activate after the http req is done
// gonna work here
}
addList(newItem): void {
}
它会像那样正常工作