angular - 需要帮助了解为什么我的组件中的 Username 属性未定义?
问题描述
我正在使用 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 的最后一行进行控制台记录时,我得到了未定义,我不明白它为什么这样做?我错过了什么?
解决方案
您没有异步使用它,为什么
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 {
}
它会像那样工作得很好
推荐阅读
- python - 当我要求它只接受整数和浮点数时,为什么我在 python 中的验证尝试接受字母?
- html - 移动设备上出现错误的响应式导航
- php - 如何使用 smarty 或 php 从 jquery 发布请求中读取数据
- angular - 一旦应用程序部署在 VPS 服务器中,如何将 Angular 前端连接到 Spring Boot 后端?
- python - sg.Output 中未对齐的 Excel 表的问题
- swift - Starscream 的 Swift 背景 websocket
- ckeditor4.x - 使用 AutoGrow 插件时 CkEditor 不再响应
- npm - 如何创建像 create-react-app 这样的自定义 npm 命令?
- amazon-web-services - Lambda:将 170mb 文件从磁盘加载到内存需要 20 多秒
- php - 将 woo rest api 连接到实时服务器 wp 多站点