Search code examples
angulartypescripthttprxjshttpclient

Angular 12 TypeError: Cannot read properties of null (reading 'length') at HttpHeaders.applyUpdate


I'm getting this error message when I make a http request in my Angular Service. This only happens when I logout but when I login the error disappears:

Here's my authentication Service:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry, map } from 'rxjs/operators';
import { JwtHelperService } from '@auth0/angular-jwt';

export interface ServerResponse {
  success: boolean;
  msg: string;
  user: any;
  token: any
}

@Injectable({
  providedIn: 'root'
})

export class AuthService {

    authToken: any;
  user: any;
    public baseUri: string = 'http://localhost:3000/users';
    public headers = new HttpHeaders().set('Content-Type', 'application/json')

  constructor(private http: HttpClient) { }

  public registerUser(user): Observable<ServerResponse> {
    return this.http.post<ServerResponse>(this.baseUri + '/register', user, { headers: this.headers });
  }

  public authenticateUser(user): Observable<ServerResponse> {
    return this.http.post<ServerResponse>(this.baseUri + '/authenticate', user, { headers: this.headers });
  }

  public getProfile(): Observable<ServerResponse> {
    this.loadToken();
    const head = this.headers.append('Authorization', this.authToken);
    return this.http.get<ServerResponse>(this.baseUri + '/profile', { headers: head });
  }

  public storeUserData(token, user) {
    localStorage.setItem('id_token', token);
    localStorage.setItem('user', JSON.stringify(user));
    this.authToken = token;
    this.user = user;
  }

  public loadToken() {
    const token = localStorage.getItem('id_token');
    this.authToken = token;
  }

  public loggedin() {
    if (localStorage.id_token == undefined ){
      return false;
    } else {
      const helper = new JwtHelperService();
      return !helper.isTokenExpired(localStorage.id_token);
    }
  }

  public logout() {
    this.authToken = null;
    this.user = null;
    localStorage.clear();
  }
}

This is what my logout function looks like in my component:

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../Services/auth.service';
import { PostService } from "../Services/post.service";
import { Router } from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';
//declare var anime: any;

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
  public isMenuCollapsed = true;
  username;
  postAuthor: string;
  posts: any;

  constructor(
    public authService: AuthService,
    private flashMessage: FlashMessagesService,
    private postService: PostService,
    private router: Router) { }

 ngOnInit(): void {}

onLogoutClick() {
    this.authService.logout();
    this.flashMessage.show('You are logged out', {cssClass: 'alert-success', timeout: 2000});
    this.router.navigate(['login']);
    return false;
  }
}

The error logs look like this:

core.js:6456 ERROR TypeError: Cannot read properties of null (reading 'length')
    at HttpHeaders.applyUpdate (http.js:236)
    at http.js:208
    at Array.forEach (<anonymous>)
    at HttpHeaders.init (http.js:208)
    at HttpHeaders.forEach (http.js:271)
    at Observable._subscribe (http.js:1713)
    at Observable._trySubscribe (Observable.js:42)
    at Observable.subscribe (Observable.js:28)
    at innerSubscribe (innerSubscribe.js:67)
    at MergeMapSubscriber._innerSub (mergeMap.js:57)

I can't figure out why this error is happening. Even though everything seems to be working fine. Any help is greatly appreciated. Thank You Very Much.


Solution

  • From what I am seeing in error and if you see the error as well it is pointing towards your HttpHeaders. The problem is you are setting your token to null on logout. Now it is for this reason you get this error only when you are logged out and not when logged in (because token is present at while you are logged in).

    Set the header only if token is available. Try the following:

    if(token) { then set your header only }