保存JWT后将JWT传递到Angular 4应用程序/重定向

保存JWT后将JWT传递到Angular 4应用程序/重定向,angular,angular-router,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',

如何将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
,如果需要,接下来会出现登录提示

,您可能只需使用grap参数并从构造函数中直接重定向,如下所示:

http://myapp.com/x?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
构造函数(路由:ActivatedRouteSnapshot,路由器:路由器)
{
localStorage.setItem('currentUser',JSON.stringify({
令牌:route.params.jwt
}));
路由器。导航(['/']);
}