首页 > 解决方案 > AngularJs 无法读取未定义的属性“订阅”

问题描述

我想在应用程序中访问我记录的用户数据,但我收到了这个错误

错误错误:未捕获(承诺中):TypeError:无法读取未定义的属性“订阅”

这是我的代码:

public user: User;

ngOnInit() {
  this.authService.user().subscribe((data) => {
    this.user = data;
  });
}

我的authService.user()功能是:

user() {
    if (this.isLoggedIn === true) {
      const headers = new HttpHeaders({
        Authorization : this.token.token_type + ' ' + this.token.access_token,
        Accept: 'application/json, text/plain',
        'Content-Type': 'application/json'
      });

      return this.http.post<User>(this.env.USERS_URL, null, { headers })
      .pipe(
        tap(user => {
          return user;
        })
      );
    }
  }

任何想法?

更新

如果我评论isLoggedIn我会得到

未捕获(承诺):TypeError:无法读取未定义的属性“token_type”类型错误:无法读取未定义的属性“token_type”

当我的用户登录时,令牌存在于数据库中

二

标签: angularionic-framework

解决方案


解决了

这是我的最终代码,它解决了我的问题

ngOnInit() {
  this.authService.getToken().then(() => { //check if user has token in DB
    if(this.authService.isLoggedIn) { // check if user is logged
      this.authService.user().subscribe(user => { // return user data
        this.user = user;
      });
    }
  });
}

希望能帮助到你。


推荐阅读