用于用户登录的Angular2 Authguard
因此,我有后端设置,如果我登录后,它会启动一个会话,如果我注销后,它会结束该会话。 我想编写Angular2 auth guard,以便它跟踪用户是否登录 //login.component.ts用于用户登录的Angular2 Authguard,angular,angular2-routing,angular2-services,angular2-directives,Angular,Angular2 Routing,Angular2 Services,Angular2 Directives,因此,我有后端设置,如果我登录后,它会启动一个会话,如果我注销后,它会结束该会话。 我想编写Angular2 auth guard,以便它跟踪用户是否登录 //login.component.ts export class LoginComponent implements OnInit { questions: any[]; error_message: string = 'Login Unsuccessful' constructor(public router: R
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);
}
}
@Injectable()
导出类身份验证服务{
私有基url:string;
公共登录:主题=新主题();
构造函数(专用http:http){
this.base\u url='1http://localhost:3000/';
}
登录(用户名:string,密码:string):可观察{
让query_url=`${this.base_url}登录`;
让payload=JSON.stringify({username:username,password:password});
返回this.http.post(查询url,有效负载)
.map(res=>res.json())
.catch((error:any)=>Observable.throw(error.json());
}
注销():可观察到{
让query_url=`${this.base_url}注销`;
返回this.http.post(查询url,null);
}
}
如何编写一个auth-guard来跟踪服务中的变量?
跟踪登录的最佳方法是什么?我知道在AngularJS中有$rootscope变量,但在Angular2中没有,所以需要处理很多
我建议大家看一下这个模块,以处理jwt令牌和身份验证。我认为这不会有什么帮助。我说的是所有的前端工作我知道,我在这里使用它,如果你想看看:。您熟悉jwt代币吗?否则,您只需在authenticationservice中创建一个可观察/主题来跟踪登录状态。但我不认为这是最好的方法,你应该使用JWT标记作为@crash状态。这是一种快速而安全的检查用户是否登录的方法。