Angular 2 - Auth0 用户配置文件,未定义

Angular 2 - Auth0 User Profile, undefined

我尝试在我的 Angular 2 项目中使用 Auth0。我正在从 Auth0 website 学习它。我的问题是用户配置文件。登录后,我调用 ngOnInit 的方法与网站示例中的方法大致相同:

if (this.auth.isAuthenticated()) {
    if (this.auth.userProfile) {
        this.profile = this.auth.userProfile;
    } else {
        this.auth.getProfile((err, profile) => {
            this.profile = profile;
        });
    }

    this.auth.alreadyExists(this.profile.sub);
}

问题是 this.auth.alreadyExists(this.profile.sub); 方法的参数 this.profile.sub

错误信息是:

ERROR 错误:未捕获(承诺):TypeError:无法读取未定义的 属性 'sub' 类型错误:无法读取未定义的 属性 'sub'。

如果我在 HTML 文件 {{profile?.sub}} 中写入并删除 this.auth.alreadyExists(this.profile.sub); 方法,它会毫无问题地显示 user_id.

不知道哪里错了

谢谢!

由于 getProfile 是异步的,因此当您调用 alreadyExists 时 profile.sub 还不存在。如果您将对 alreadyExists 的调用移动到 getProfile 回调中,那么您应该没问题。