【问题标题】:i want to perform a redirect from a service in my angular 2 app我想从我的 Angular 2 应用程序中的服务执行重定向
【发布时间】:2017-06-18 01:51:03
【问题描述】:

我正在学习 Angular 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 功能,但我的用户仍然看到登录页面。

【问题讨论】:

    标签: angular auth0


    【解决方案1】:

    不要在 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']);
    });
    

    【讨论】:

    • 这行得通,但现在它只显示了我的仪表板的路由器插座部分,而不显示我在页面上的其他元素,如侧边栏。
    猜你喜欢
    • 2017-06-21
    • 1970-01-01
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多