I've successfully implemented Auth0 authentication in my Angular 2 application. However, upon signing in, I encounter an error stating "Cannot read property 'picture' of null." Oddly enough, if I refresh the page, the user is shown as logged in and the image appears without any errors in the console.
Here's the error message I receive: https://i.sstatic.net/dXTwc.png
For those interested, here's the link to the GitHub repository: https://github.com/cstodor/Auth0Lock-Angular2
Below is the code snippet for the affected element in header.component.html
:
<span *ngIf="auth.authenticated()">
<img class="img-circle" width="25" height="25" src="{{ profile.picture }}"> {{ profile.nickname }}
</span>
header.component.ts
:
profile: any;
constructor(private auth: Auth) {
this.profile = JSON.parse(localStorage.getItem('profile'));
}
auth.service.ts
import { Injectable } from '@angular/core';
import { tokenNotExpired } from 'angular2-jwt';
import { myConfig } from './auth.config';
let Auth0Lock = require('auth0-lock').default;
@Injectable()
export class Auth {
// Configure Auth0
lock = new Auth0Lock(myConfig.clientID, myConfig.domain, {});
profile: any;
constructor(private router: Router) {
this.lock.on("authenticated", (authResult: any) => {
this.lock.getProfile(authResult.idToken, function (error: any, profile: any) {
if (error) {
throw new Error(error);
}
localStorage.setItem('id_token', authResult.idToken);
localStorage.setItem('profile', JSON.stringify(profile));
console.log('PROFILE: ' + profile);
});
});
}
public login() {
// Display the widget
this.lock.show();
};
public authenticated() {
// Check for unexpired JWT
return tokenNotExpired();
};
public logout() {
// Remove tokens from localStorage
localStorage.removeItem('id_token');
localStorage.removeItem('profile');
};
}
Any advice on how to resolve this issue? Your input would be greatly appreciated!