我已經將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