我正在学习角度2,我正在尝试创建一个场景,我的用户会看到主页并使用Auth0登录到我的应用程序,之后我希望用户从身份验证服务中重定向到仪表板页面。
import { Injectable } from '@angular/core';
import { tokenNotExpired } from 'angular2-jwt';
import { myConfig } from './auth.config';
import {Router} from "@angular/router";
// Avoid name not found warnings
declare var Auth0Lock: any;
@Injectable()
export class Auth {
// Configure Auth0
lock = new Auth0Lock(myConfig.clientID, myConfig.domain, {});
constructor(private router:Router) {
// Add callback for lock `authenticated` event
this.lock.on('authenticated', (authResult) =>
{
this.lock.getProfile(authResult.idToken,function (error: any, profile: any)
{
if(error)
{
throw new Error;
}
localStorage.setItem('id_token', authResult.idToken);
localStorage.setItem('profile', JSON.stringify(profile));
this.router.navigate(['/dashboard']);
});
});
}
public login() {
// Call the show method to display the widget.
this.lock.show();
};
public authenticated() {
// Check if there's an unexpired JWT
// It searches for an item in localStorage with key == 'id_token'
return tokenNotExpired();
};
public logout() {
// Remove token from localStorage
localStorage.removeItem('id_token');
localStorage.removeItem('profile');
this.router.navigate(['/login']);
};
}
我正在使用Auth0提供的身份验证服务模板,然后我在登录功能中添加了router.navigate功能,但我的用户仍然看到了登录页面。
答案 0 :(得分:4)
不要在TypeScript类中使用function
...这会弄乱this
上下文。仅使用箭头函数表示法() => {}
。这将保持this
上下文与类的上下文:
this.lock.getProfile(authResult.idToken, (error: any, profile: any) => { //here
if(error)
{
throw new Error;
}
localStorage.setItem('id_token', authResult.idToken);
localStorage.setItem('profile', JSON.stringify(profile));
this.router.navigate(['/dashboard']);
});