2017-10-17 44 views
0

如何将JWT传递到Angular 4应用程序中,保存令牌,然后导航到主页?我想下面的语法,但我担心的是依靠ngAfterViewInit是不是这样做的正确方法...将JWT传入Angular 4 app /重定向后保存JWT

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

你或许可以只使用ActivatedRouteSnapshot,虎视眈眈PARAMS和构造右出重定向这样的:

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