所以我有後端設置,如果我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中不可用
您應該使用JWT令牌作爲@crash狀態。這是檢查用戶是否登錄的快速且安全的方法。 –