0

私はPOSTログインをしてからセッションを開始し、POSTログアウトすればそのセッションを終了するようにバックエンドの設定をしています。 ユーザーがログインしているかどうかを追跡するように、Angular2認証ガードを書きたいと思います。ユーザーログインのためのAngular2 Authguard

//login.component.ts

export class LoginComponent implements OnInit { 
    questions: any[]; 
    error_message: string = 'Login Unsuccessful' 

    constructor(public router: Router, 
    private authenticationService: AuthenticationService, 
    question_service: LoginQuestionService) { 

    this.questions = question_service.getQuestions(); 
    this.authenticationService.logged_in.subscribe((value) => { 
     console.log("Login Status: " + value); 
    }); 
    } 

    ngOnInit() { 
    } 

    formSubmitted(data): void { 
    this.login(data.username, data.password); 
    } 


    login(username, password) { 
    event.preventDefault(); 
    this.authenticationService.login(username, password) 
    .subscribe(
     response => { 
     this.authenticationService.logged_in.next(true); 
     this.router.navigate(['home']); 
     }, 
     error => { 
     this.authenticationService.logged_in.next(false); 
     alert(this.error_message); 
     this.router.navigate(['login']); 
     console.log(error); 
     } 
    ); 
    }; 

//authenticationservice.tsサービスに変数を追跡して認証ガードを書くに行くかどう

@Injectable() 
export class AuthenticationService {  
    private base_url: string; 
    public logged_in: Subject<boolean> = new Subject(); 
      
    constructor(private http: Http) { 
     this.base_url = 'http://localhost:3000/'; 
    } 

    login(username: string, password: string): Observable<Response> { 
     let query_url = `${this.base_url}login`; 
     let payload = JSON.stringify({username: username, password: password}); 
     return this.http.post(query_url, payload) 
     .map(res => res.json()) 
     .catch((error:any) => Observable.throw(error.json())); 
    } 

    logout(): Observable<Response>{ 
     let query_url = `${this.base_url}logout`; 
     return this.http.post(query_url, null); 
    } 
} 

? ログインを追跡する最良の方法は何ですか?私はAngularJSで知っていますが、$ rootscope変数はありますが、Angular2ではありません。

+0

JWTトークンを@crash状態として使用する必要があります。これは、ユーザーがログインしているかどうかを確認するための迅速かつ安全な方法です。 –

答えて

0

これは非常に処理が大変です。

私は、このモジュールhttps://github.com/auth0/angular2-jwtを見て、jwtトークンと認証を一般的に処理することをお勧めします。

+0

私はそれがthoを助けるとは思わない。私はすべてのフロントエンドの仕事について話しています – PowerLove

+0

私が知っている、私はあなたがそれを見てみたい場合はここでそれを使用しました:https://github.com/damnko/angular2-django-movies。 jwtトークンに精通していますか?それ以外の場合は、認証サービスに監視対象/件名を作成してログイン状態を追跡することができます。しかし、私はそれが最良のアプローチだとは思わない – crash

関連する問題