Encountering an issue with Angular 12 where a TypeError is being thrown, specifically stating "Cannot read properties of null (reading 'length') at

I encountered an error message while making a http request in my Angular Service. Strangely, this error only occurs after I logout, but it disappears upon logging back in:

Below is the code snippet of 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 });
  }

  ...

This is how the logout function in my component is implemented:

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 {
  ...

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 point to the following issue:

core.js:6456 ERROR TypeError: Cannot read properties of null (reading 'length')
    at HttpHeaders.applyUpdate (http.js:236)
    at http.js:208
    ...

Despite everything seeming to work fine, I am still puzzled by this error. Any insight or assistance would be greatly appreciated. Thank you.

Answer №1

After carefully examining the error, it appears that the issue lies with your HttpHeaders. The reason you are encountering this error only when logged out is because you are setting your token to null upon logout.

To resolve this, ensure that the header is set only if a token is available. You can achieve this by implementing the following:

if(token) { then set your header only }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Mastering the Art of Promises in RXJS Observables

After thoroughly researching SO, I stumbled upon numerous questions and answers similar to mine. However, I suspect that there might be gaps in my fundamental understanding of how to effectively work with this technology stack. Currently, I am deeply enga ...

The value control input does not get properly updated by ngModelChange

Having difficulty updating an input as the user types. Trying to collect a code from the user that follows this format: 354e-fab4 (2 groups of 4 alphanumeric characters separated by '-'). The user should not need to type the '-', as it ...

Issue with NgRx Testing: Callback in subscribe method fails to update during testing

I am currently working on testing a component that is responsible for editing shopping list items. Upon first loading, the component receives state values through store.select, which are: editedIngredient: null, editedIngredientIndex: -1 Based on these ...

TypeScript and Redux mapDispatchToProps are not in sync

Below is my React component written in TypeScript: import React from 'react'; import {connect, ConnectedProps} from 'react-redux'; import logo from './assets/logo.png'; // import { Counter } from './features/counter/Count ...

Utilize Typescript Functions to Interact with GeoJSON Data in Palantir Foundry

Working on a map application within Palantir utilizing the workshop module. My goal is to have transport routes showcased along roads depending on user inputs. I am familiar with displaying a route using GeoJSON data, but I'm wondering if there is a w ...

Leveraging Shared and CoreModule in Ionic

In the recommended styleguide found at https://angular.io/guide/styleguide#core-feature-module, it is suggested to implement a SharedModule and CoreModule in an Angular application. I am curious if utilizing these modules would also be beneficial in an Io ...

Navigating to specific rows in a primeng virtualscroll table using the scrollToIndex

Utilizing Primeng virtual scroll table in Angular to manage large datasets in an array. I am interested in using the scrollToIndex. Is there an equivalent of cdk-virtual-scroll-viewport in Primeng table? I need the functionality where, upon a user clicking ...

Expanding a TypeScript type by creating an alias for a property

I am working on defining a type that allows its properties to be "aliased" with another name. type TTitle: string; type Data<SomethingHere> = { id: string, title: TTitle, owner: TPerson, } type ExtendedData = Data<{cardTitle: "title&qu ...

Is it possible for a component to have multiple templates that can be switched based on a parameter?

Scenario My task is to develop a component that fetches content from a database and displays it on the page. There needs to be two components working together to create a single page, following a specific component tree structure. DataList - receives ful ...

Issue with locating image source in Angular 4

I'm struggling to source an image using angular 4. It keeps giving me an error message saying that the image cannot be found. Here is my folder structure: app_folder/ app_component/ - my_componenet - image_folder/ - myimage I am trying to ...

The function you are trying to call is not valid... the specified type does not have any call signatures [ts 2349

Having some trouble using functions from Observable Plot example with a marimekko chart in my TypeScript project. I encountered an error on this particular line: setXz(I.map((i) => sum.get(X[i]))) The code snippet causing the issue is as follows: fu ...

Develop an extensive Typescript and React shared library

Trying to develop a shared React and Typescript library has been quite challenging. Configuring the project workspace to work on both the library and application simultaneously has proven to be more difficult than anticipated. project ├─ app │ ├ ...

Why do I keep getting an ExpressionChangedAfterItHasBeenChecked error after trying to update a random color in an

Is there a way to assign a random color from an array without causing the error message: "ExpressionChangedAfterItHasBeenChecked"? Even though the color of the chip changes quickly before the message appears, it seems like it's working. How can I reso ...

Adding a blank line in an Angular table using primeNG to display database information requires a specific method

In my Angular application, I am utilizing primeNG table to display data fetched from a database. The table comes with 'add' and 'delete' buttons for user interaction. To view the interface, click on this link: https://i.stack.imgur.com/ ...

Working with Yarn and Webpack: Incorporating a TypeScript .ts file from an external Node directory not controlled by Yarn/Webpack

I am currently working on a k6 project for load testing, utilizing Yarn and Webpack. This project is stored within a sub-folder of a larger repository that primarily uses npm Node modules. My goal is to access a secret from AWS's Secrets Manager in t ...

The plugin "proposal-numeric-separator" was not found. Please make sure that there is a corresponding entry for it in the ./available-plugins.js file

{ "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "myProjects", "projects": { "uniqueApp": { "projectType": "web-app", "schematics": {}, "root": "", "sourceRoot": "src", ...

What is the best way to define the type of an object when the Key is already known?

If I have the code snippet below, how can I properly define the data object type based on the known value of data.type? In this scenario, I aim to assign a specific type to data when its type property is either "sms" or "email" const payload = '{&quo ...

The loading time for the Docker index HTML file page is unacceptably slow

Sample Dockerfile: FROM ubuntu:22.04 RUN apt-get update RUN apt-get install -y nginx COPY -r dist/ /var/www/html/ CMD service nginx start && tail -F /var/log/nginx/error.log After that, run the following commands: docker build -t website . docker ...

Why is HttpURLConnection sending a JSON object encoded as base64?

Here is the code snippet I am working with: URL url = new URL("http://httpbin.org/post"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.s ...

Incorporating Copyleaks SDK into Angular: A Seamless Integration

Currently, I'm in the process of implementing the Copyleaks SDK with Angular to conduct plagiarism checks on two text area fields within an HTML form. Within the form, my goal is to incorporate two buttons: one to check for plagiarism on one text area ...