Angular 4 - 用户在刷新之间注销

时间:2018-02-14 19:38:39

标签: angular jwt

我正在构建一个Angular应用程序(使用Django作为我的后端)。问题是,每次页面重新加载我的用户都会自动退出。我刚刚开始学习Angular,所以如果答案太明显,请原谅我。 这是我在component.ts中的登录功能:

  login(username, password) {
    this.auth.login(username, password)
    .subscribe(res => {
      if (res) {
        this.router.navigate(['/']);
      } else {
        this.error = this.error = 'Username or password is incorrect.';
      }
    });
  } 

这是我在auth.service中的登录功能:

    login(username, password) : Observable<boolean> {
      const authUrl = `http://127.0.0.1:8000/api-token-auth/`;
      var credentials = new Credentials(username, password);
      return this.http.post(authUrl, credentials, httpOptions).pipe(
        map(results => {
          if (results['token']) {
            localStorage.setItem('bangular-jwt-token', results['token']);
            this.isLoggedIn = true;

            this.username = username;
            this.user.getUser(this.username).subscribe((users) => {
             this.users = users; 
            });                 
             return true;
          } else {
             return false;
          }
        }),
          catchError(this.eh.handleError<boolean>(`login 
            username=${username}`,false))
          );
     }

0 个答案:

没有答案