2017-10-17 6 views
0

Angular 4アプリにJWTを渡してトークンを保存し、ホームページに移動するにはどうすればよいですか?JWTをAngular 4 app/Redirectにパスします。

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を呼び出すことです...私は、次の構文をしようとしているが、私はngAfterViewInitに頼ることは、これを行うのが正しい方法ではないことを心配しています

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

私のホームページやその他のアプリケーションではAuthGuardが使用されているため、ログインのプロンプトはの場合はとなります。

答えて

1

あなたはおそらくActivatedRouteSnapshot、GRAPのparamsを使用して、次のようにコンストラクタから右に出てリダイレクトすることができます。

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