0

所以我有後端設置,如果我POST登錄,然後它開始一個會話,如果我註銷登錄,它會結束該會話。 我想編寫Angular2 auth guard,以便跟蹤用戶是否登錄。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); 
    } 
} 

將如何去寫一個auth戒備的跟蹤變量的服務? 跟蹤登錄的最佳方式是什麼?我知道在AngularJS中,有$ rootcope變量,但在Angular2中不可用

+0

您應該使用JWT令牌作爲@crash狀態。這是檢查用戶是否登錄的快速且安全的方法。 –

回答

0

在SO中處理相當多。

我建議看看這個模塊https://github.com/auth0/angular2-jwt來處理一般的jwt令牌和認證。

+0

我不認爲這會幫助tho。我在談論所有前端工作 – PowerLove

+0

我知道,如果你想看看它,我在這裏使用它:https://github.com/damnko/angular2-django-movies。你熟悉jwt令牌嗎?否則,您只需在身份驗證服務中創建一個可觀察/主題以跟蹤登錄狀態。但我認爲這不是最好的方法 – crash