Search code examples
angularundefinedauth0

Angular 2 - Auth0 User Profile, undefined


I try to use Auth0 in my Angular 2 project. I'm learning it form Auth0 website. My problem is with the user profile. After I log in, I call on ngOnInit approximately the same method as in the example from the website:

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);
}

The problem is the this.auth.alreadyExists(this.profile.sub); method's parameter this.profile.sub.

The error message is:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'sub' of undefined TypeError: Cannot read property 'sub' of undefined.

If I write in the HTML file {{profile?.sub}} and delete the this.auth.alreadyExists(this.profile.sub); method, it displays with no problem the user_id.

I don't know where is the mistake.

Thank you!


Solution

  • Since getProfile is asynchronous, profile.sub doesn't exist yet when you call alreadyExists. If you move the call to alreadyExists up into the getProfile callback then you should be fine.