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

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

我在 Angular 服务中发出 http 请求时收到此错误消息。这仅在我注销时发生,但在我登录时错误消失:

这是我的身份验证服务:

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();
  }
}

这是我的注销功能在我的组件中的样子:

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;
  }
}

错误日志如下所示:

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)

我不明白为什么会出现这个错误。尽管一切似乎都运行良好。任何帮助是极大的赞赏。非常感谢。

从我看到的错误来看,如果您也看到错误,它指向您的 HttpHeader。问题是您在注销时将令牌设置为空。现在正是出于这个原因,您仅在注销而不是登录时才会收到此错误(因为令牌在您登录时存在)。

仅当令牌可用时才设置 header。请尝试以下操作:

if(token) { then set your header only }