title: ERROR:TypeError: Cannot read property 'username' of undefined
body: <pre><code>TypeError: Cannot read property 'username' of undefined
      at Object.eval [as updateDirectives] (AppComponent.html:6)
      at Object.debugUpdateDirectives [as updateDirectives] (core.js:36055)
      at checkAndUpdateView (core.js:35067)
      at callViewAction (core.js:35433)
      at execEmbeddedViewsAction (core.js:35390)
      at checkAndUpdateView (core.js:35068)
      at callViewAction (core.js:35433)
      at execComponentViewsAction (core.js:35361)
      at checkAndUpdateView (core.js:35074)
      at callWithDebugContext (core.js:36407)
  </code></pre>
  
  <p>My code was working fine..Accidentally I happened to have deleted the user but recreated the profile..since then the above error is showing while trying to log in with the user..Attached is the component.ts..Can I get some help?</p>
  
  <p>app.component.ts</p>
  
  <pre><code>import {Component, OnInit} from '@angular/core';
  import {UserService} from './user.service';
  import {throwError} from 'rxjs';
  
  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
  })
  export class AppComponent implements OnInit {
  
    public users: any;
    /**
     * An object representing the user for the login form
     */
    public user: any;
  
    constructor(public _userService: UserService) { }
  
    ngOnInit() {
      this.user = {
        username: '',
        password: ''
      };
    }
  
    login() {
      this._userService.login({'username': this.user.username, 'password': this.user.password});
    }
  
    refreshToken() {
      this._userService.refreshToken();
    }
  
    logout() {
      this._userService.logout();
    }
  
    getUsers() {
      this.users = this._userService.getUsers();
     }
  }
  </code></pre>
  
  <p>This is the template..Though I havent altered anything in this file..
  app.component.html</p>
  
  <pre><code>&lt;h2&gt;Log In&lt;/h2&gt;
  &lt;div class="row" *ngIf="!_userService.token"&gt;
    &lt;div class="col-sm-4"&gt;
      &lt;label&gt;Username:&lt;/label&gt;&lt;br /&gt;
      &lt;input type="text" name="login-username" [(ngModel)]="user.username"&gt;
      &lt;span *ngFor="let error of _userService.errors.username"&gt;&lt;br/&gt;{{ error }}&lt;/span&gt;&lt;/div&gt;
    &lt;div class="col-sm-4"&gt;
      &lt;label&gt;Password:&lt;/label&gt;&lt;br /&gt;
      &lt;input type="password" name="login-password" [(ngModel)]="user.password"&gt;
      &lt;span *ngFor="let error of _userService.errors.password"&gt;&lt;br/&gt;{{ error }}&lt;/span&gt;
    &lt;/div&gt;
    &lt;div class="col-sm-4"&gt;
      &lt;button (click)="login()" class="btn btn-primary"&gt;Log In&lt;/button&gt;&amp;nbsp;
    &lt;/div&gt;
    &lt;div class="col-sm-12"&gt;
      &lt;span *ngFor="let error of _userService.errors.non_field_errors"&gt;{{ error }}&lt;br /&gt;&lt;/span&gt;
    &lt;/div&gt;
  &lt;/div&gt;
  &lt;div class="row" *ngIf="_userService.token"&gt;
    &lt;div class="col-sm-12"&gt;You are logged in as {{ _userService.username }}.&lt;br /&gt;
      Token Expires: {{ _userService.token_expires }}&lt;br /&gt;
      &lt;button (click)="refreshToken()" class="btn btn-primary"&gt;Refresh Token&lt;/button&gt;&amp;nbsp;
      &lt;button (click)="getUsers()" class="btn btn-primary"&gt;Get Users&lt;/button&gt;
      &lt;button (click)="logout()" class="btn btn-primary"&gt;Log Out&lt;/button&gt;&amp;nbsp;
    &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>user.service.ts</p>
  
  <pre><code>import {Injectable} from '@angular/core';
  import {HttpClient, HttpHeaders} from '@angular/common/http';
  
  
  @Injectable()
  export class UserService {
  
    // http options used for making API calls
    private httpOptions: any;
  
    // the actual JWT token
    public token: string;
  
    // the token expiration date
    public token_expires: Date;
  
    // the username of the logged in user
    public username: string;
  
    // user array
    public userList: any = [];
  
    // error messages received from the login attempt
    public errors: any = [];
  
    constructor(private http: HttpClient) {
      this.httpOptions = {
        headers: new HttpHeaders({'Content-Type': 'application/json'})
      };
    }
  
    // Uses http.post() to get an auth token from djangorestframework-jwt endpoint
    public login(user) {
      this.http.post('/api-token-auth/', JSON.stringify(user), this.httpOptions).subscribe(
        data =&gt; {
          console.log('login success', data);
          this.updateData(data['token']);
          localStorage.setItem('token', data['token']);
        },
        err =&gt; {
          this.errors = err['error'];
        }
      );
    }
  
    /**
     * Refreshes the JWT token, to extend the time the user is logged in
     */
    public refreshToken() {
      this.http.post('/api-token-refresh/', JSON.stringify({token: this.token}), this.httpOptions).subscribe(
        data =&gt; {
          console.log('refresh success', data);
          this.updateData(data['token']);
          localStorage.setItem('token', data['token']);
        },
        err =&gt; {
          console.error('refresh error', err);
          this.errors = err['error'];
        }
      );
    }
  
    public getUsers() {
      this.http.get('/api-users/', {
        headers: new HttpHeaders({
          'Content-type': 'application/json',
          'Authorization': localStorage.getItem('token')
        })
      }).subscribe(
        data =&gt; {
          this.userList = data['token'];
        },
        err =&gt; {
          console.error('authorization error', err);
          this.errors = err['error'];
        }
      );
    }
  
    public logout() {
      this.token = null;
      this.token_expires = null;
      this.username = null;
      localStorage.removeItem('token');
    }
  
    private updateData(token) {
      this.token = token;
      this.errors = [];
  
      // decode the token to read the username and expiration timestamp
      const token_parts = this.token.split(/\./);
      const token_decoded = JSON.parse(window.atob(token_parts[1]));
      this.token_expires = new Date(token_decoded.exp * 1000);
      this.username = token_decoded.username;
    }
  
  }
  </code></pre>