我已经将Auth0验证集成到Angular 2应用程序中,并且在登录后,我得到这个”Can not read property'picture of null“error,但是,如果我刷新页面,则表明用户已登录,并且控制台中显示的图像没有错误。Angular 2 + Auth0“登录后无法读取null的属性'图片'
链接到GitHub的库: https://github.com/cstodor/Auth0Lock-Angular2
这是受影响的元素在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)); // We will wrap the profile into a JSON object as In local Storage you can only store strings
console.log('PROFILE: ' + profile);
});
});
}
public login() {
// Call the show method to display the widget.
this.lock.show();
};
public authenticated() {
// Check if there's an unexpired JWT
// This searches for an item in localStorage with key == 'id_token'
return tokenNotExpired();
};
public logout() {
// Remove tokens from localStorage
localStorage.removeItem('id_token');
localStorage.removeItem('profile');
};
}
谁能给我这个问题的一些建议吗?
射击,因为我没有做过太多ANG2但''将是我的猜测。我认为使用'src'仍然存在ang2中的问题,就像它在ang1中一样 – Ronnie
你确定profile.picture不是null吗?此外,在src属性中使用{{profile.picture}}等角度标记不能按预期工作。你会想用ng-src代替。 – jbrown
@Ronnie错过了...它没有解决问题,但好点。 – Todor