2016-11-29 73 views
1

我已经将Auth0验证集成到Angular 2应用程序中,并且在登录后,我得到这个”Can not read property'picture of null“error,但是,如果我刷新页面,则表明用户已登录,并且控制台中显示的图像没有错误。Angular 2 + Auth0“登录后无法读取null的属性'图片'

这是我的错误: enter image description here

链接到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'); 
    }; 
} 

谁能给我这个问题的一些建议吗?

+1

射击,因为我没有做过太多ANG2但''将是我的猜测。我认为使用'src'仍然存在ang2中的问题,就像它在ang1中一样 – Ronnie

+0

你确定profile.picture不是null吗?此外,在src属性中使用{{profile.picture}}等角度标记不能按预期工作。你会想用ng-src代替。 – jbrown

+0

@Ronnie错过了...它没有解决问题,但好点。 – Todor

回答

1

profile当ngIf进程抛出异常时不存在。 将您的ngIf更改为*ngIf="auth.authenticated() && profile"以延迟处理直至profile存在。

我猜你在等待承诺解决,或者你没有设置profile你auth后的任何地方,这就是为什么profile为空。

+0

我推迟了化身图像的处理,错误不再显示在控制台中,但图像也没有出现。 也许重定向用户后身份验证将解决问题,但我认为这将是一个糟糕的解决方法。 – Todor

+0

@mrTodor,配置文件如何设置?你能否在问题中包含初始化profile变量的代码部分? –

+0

@mrTodor,它绝对看起来像“配置文件”从未设置。你在哪里分配?您可以向我们展示验证后运行的代码吗? –

1

最后,我们设法通过朋友的帮助解决了这个问题。 那么,问题是,profile会从localStorage数据创建HeaderComponent时,但localStorage只有当用户成功登录的价值。

对于这种情况,你必须订阅auth的个人资料更新和意志 从它获取更新的配置文件。

更新的代码可以在GitHub的仓库中找到:在黑暗中
https://github.com/cstodor/Auth0Lock-Angular2

相关问题