首页 > 解决方案 > 需要帮助了解为什么我的组件中的 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 的最后一行进行控制台记录时,我得到了未定义,我不明白它为什么这样做?我错过了什么?

标签: angular

解决方案


您没有异步使用它,为什么

    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 {
  }

它会像那样工作得很好


推荐阅读