保存JWT后,将JWT传递给Angular 4 app / Redirect

时间:2017-10-17 17:07:32

标签: angular angular-router

如何将JWT传递到Angular 4应用程序,保存令牌,然后导航到主页?我尝试使用以下语法,但我担心依赖ngAfterViewInit并不是正确的做法...

import { Component, OnInit, OnDestroy, AfterViewInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-xfer',
  templateUrl: './xfer.component.html',
  styleUrls: ['./xfer.component.css']
})
export class XferComponent implements OnInit, OnDestroy {

  sub: any

  constructor(private route: ActivatedRoute, private router: Router) { }

  ngOnInit() {
    this.sub = this.route
      .queryParams
      .subscribe(params => {
        localStorage.setItem('currentUser', JSON.stringify({
          token : params['jwt']
        }))
      });
  }

  ngOnDestroy(){
    this.sub.unsubscribe();
  }

  ngAfterViewInit(){
    this.router.navigate(['/']);
  }

}

我的目标是从另一个应用程序中调用此URL:

http://myapp.com/x?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

由于我的主页和应用的其余部分正在使用AuthGuard,因此如果需要,则会提示登录

1 个答案:

答案 0 :(得分:1)

您可以使用ActivatedRouteSnapshot,grap params并从构造函数中重定向,如下所示:

constructor(route: ActivatedRouteSnapshot, router: Router)
{
  localStorage.setItem('currentUser', JSON.stringify({
      token : route.params.jwt
    }));
  router.navigate(['/']);
}