Angular2 Authguard用于用户登录

时间:2017-06-29 13:34:32

标签: angular angular2-routing angular2-services angular2-directives

所以我有后端设置,如果我POST登录,那么它启动会话,如果我POST注销,它结束该会话。 我想编写Angular2 auth guard,以便跟踪用户是否登录。

// login.component.ts

Sub SomeHiddenRoutine(bDummy As Boolean = False)
    'Routine can be called as usual using:
    SomeHiddenRoutine
End Sub

// authenticationservice.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);
      }
      );
  };

如何编写一个跟踪服务中变量的auth警卫? 跟踪登录的最佳方法是什么?我知道在AngularJS中,有$ rootcope变量,但在Angular2

中没有

1 个答案:

答案 0 :(得分:0)

在SO中要处理的事情非常多。

我建议看一下这个模块https://github.com/auth0/angular2-jwt来处理jwt令牌和身份验证。