我正在学习角度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']);
};
}
Run Code Online (Sandbox Code Playgroud)
我正在使用Auth0提供的模板进行身份验证服务,然后在登录功能中添加了router.navigate功能,但仍向我的用户显示登录页面。
不要function在TypeScript类中使用...这会弄乱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']);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1301 次 |
| 最近记录: |