Angular 需要帮助了解组件中的用户名属性未定义的原因吗?

Angular 需要帮助了解组件中的用户名属性未定义的原因吗?,angular,Angular,我正在使用angular和我的ngOnInit订阅数据并将其设置为我的用户名属性。我不明白的是,当我使用console.log(this.username)时,根据我放置控制台日志的代码行,我将无法定义,我不明白它为什么这样做 export class DashboardComponent implements OnInit { username: string; ngOnInit() { this.authService.getProfile().subscribe(prof

我正在使用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
  }
导出类仪表板组件实现OnInit{
用户名:字符串;
恩戈尼尼特(){
this.authService.getProfile().subscribe(profile=>{
this.username=profile.user.username;
console.log(this.username){
控制台日志(err);
返回false;
});
这个是.getList();

console.log(this.username);您没有在异步中使用它为什么

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

它可以像那样正常工作

这是因为它是异步的——它是在
之前执行的。用户名
已设置为@CuongVo的可能副本调用您的
getList
subscribe
内部,或者使用一些Rxjs操作符将getList调用放在subscribe回调内部(您标记的部分)“在这里工作”)。是的,从subscribe callabck中记录,但看起来您已经在这样做了