Angular 4 - User gets logged out between refreshes

Kelly Koutsioubi Source

I'm building an Angular application (using Django as my backend). The problem is that every time the page reloads my user gets automatically signed out. I just started learning Angular, so please forgive me if the answer is too obvious. Here is my login function in 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.';
      }
    });
  } 

And here is my login function in 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))
          );
     }
angularjwt

Answers

comments powered by Disqus