所以我有后端设置,如果我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状态。这是检查用户是否登录的快速且安全的方法。 –