i get error Cannot read properties of undefined (reading 'include')

Issue

I get this error when i click login button in my login page
: this error is here :
Cannot read properties of undefined (reading ‘include’) when i call
window.location.reload();
what is the problem, I searched but did not find the problem
I am thankful with your guidance

my ts code is here :

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../_services/auth.service';
import { TokenStorageService } from '../_services/token-storage.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  form: any = {
    username: null,
    password: null
  };
  isLoggedIn = false;
  isLoginFailed = false;
  errorMessage = '';
  roles: string[] = [];

  constructor(private authService: AuthService, private tokenStorage: TokenStorageService) { }

  ngOnInit(): void {
    if (this.tokenStorage.getToken()) {
      this.isLoggedIn = true;
      this.roles = this.tokenStorage.getUser().roles;
    }
  }

  onSubmit(): void {
    const { username, password } = this.form;

    this.authService.login(username, password).subscribe(
      data => {
        this.tokenStorage.saveToken(data.accessToken);
        this.tokenStorage.saveUser(data);

        this.isLoginFailed = false;
        this.isLoggedIn = true;
        this.roles = this.tokenStorage.getUser().roles;
        this.reloadPage();
      },
      err => {
        this.errorMessage = err.error.message;
        this.isLoginFailed = true;
      }
    );
  }

  reloadPage(): void {
    window.location.reload();
  }
}

and my html code is

 <div id="image">
<div class="container">

  <div class="row justify-content-center">
  <div class="col-sm-10 col-md-8 col-lg-6 col-xl-5   p-5 ">
    <mat-card>
      <mat-card-header >
        <mat-card-title> </mat-card-title>
      </mat-card-header>
      <mat-card-content>
    <img src="https://s4.uupload.ir/files/user3_r3fq.png" class="p-2">
      <form   *ngIf="!isLoggedIn"
        name="form"
        (ngSubmit)="f.form.valid && onSubmit()"
        #f="ngForm"
        novalidate
      >
        <div class="form-group justify-content-center ">
          <mat-form-field >
          <label for="username"></label>
          <i class="fa fa-user icon"></i>
          <input matInput
            type="text"
            name="username"
            placeholder="Username"
            [(ngModel)]="form.username"
            required
            #username="ngModel"
          /></mat-form-field>
          <div id="mes"
            role="alert"
            *ngIf="username.errors && f.submitted"
          >
          please enter user name
          </div>
        </div>

        <div class="form-group">    <mat-form-field>
          <label for="password"></label>
          <input matInput
            type="password"
  placeholder="Password"
            name="password"
            [(ngModel)]="form.password"
            required
            minlength="4"
            #password="ngModel"
          />

        </mat-form-field>
          <div

            role="alert"
            *ngIf="password.errors && f.submitted"
          >
            <div id="mes" *ngIf="password.errors.required">Please Enter pass</div>
            <div *ngIf="password.errors.minlength">
              Password must be at least 6 characters
            </div>
          </div>
        </div>
        <div >
          <button mat-raised-button class="btn btn-primary" >
           <span>Login</span>
          </button>

        </div>
        <div >
          <div

            role="alert"
            *ngIf="f.submitted && isLoginFailed"
          >
            Login failed: {{ errorMessage }}
          </div>
        </div>
      </form>
    </mat-card-content>
    </mat-card>
      <div  *ngIf="isLoggedIn">
        Logged in as {{ roles }}.
      </div>

    </div>

  </div>
</div>
</div>

and my user.service.ts is

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
const API_URL = 'http://localhost:8080/api/test/';

@Injectable({
  providedIn: 'root'
})
export class UserService {
  constructor(private http: HttpClient) { }

  getPublicContent(): Observable<any> {
    return this.http.get(API_URL + 'all', { responseType: 'text' });
  }

  getUserBoard(): Observable<any> {
    return this.http.get(API_URL + 'user', { responseType: 'text' });
  }

  getModeratorBoard(): Observable<any> {
    return this.http.get(API_URL + 'mod', { responseType: 'text' });
  }

  getAdminBoard(): Observable<any> {
    return this.http.get(API_URL + 'admin', { responseType: 'text' });
  }
}

and my auth.service.ts is

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
const AUTH_API = 'http://192.168.1.135:8282/api/Users/authenticate';
const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  m:any;
  constructor(private http: HttpClient) { }

  login(username: string, password: string): Observable<any> {
  this.m= this.http.post(AUTH_API , {username,password}, httpOptions);
  console.log(this.m);
  return this.m;
 }

  register(username: string, email: string, password: string): Observable<any> {
    return this.http.post(AUTH_API + 'signup', {
      username,
      email,
      password
    }, httpOptions);
  }
}

Solution

Seem you have issues in this line, you need to check if getUser is returning what you need. To suppress the error you need to change:

this.roles = this.tokenStorage.getUser().roles;

Try changing to:

this.roles = this.tokenStorage.getUser()?.roles;

Answered By – Ritesh Waghela

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published