angularangular-httpclientangular-httpclient-interceptors

HTTP GET throws TypeError: Cannot read properties of undefined (reading 'length')


I want to use a simple method to check for internet connectivity. We have a file hosted on a server and I simply want to check that we can see it.

The file contains:

{
    "status": "success"
}

In my Angular component:

#http = inject(HttpClient);
isOnline: boolean;

updateOnlineStatus(url: string): void {
    console.log(this.#CLASS_NAME + '.updateOnlineStatus() - url', url);
    
    this.#http.get<any>(url).pipe(
        catchError((error) => {
            console.log(this.#CLASS_NAME + '.updateOnlineStatus(), error', error);
            this.isOnline = false;
            return of(null);
        })
    ).subscribe(response => {
        if (response && response.status === 'success') {
            this.isOnline = true;
        } else {
            this.isOnline = false;
        }
    });
}

But when I call the method, I get:

LoginPage.updateOnlineStatus() - url https://xxx/status.json
login.component.ts:288 LoginPage.updateOnlineStatus(), error TypeError: Cannot read 
properties of undefined (reading 'length')
at HttpHeaders.applyUpdate (http.mjs:222:27)
at http.mjs:195:58
at Array.forEach (<anonymous>)
at HttpHeaders.init (http.mjs:195:33)
at HttpHeaders.forEach (http.mjs:263:14)
at Observable._subscribe (http.mjs:2116:29)
at Observable._trySubscribe (Observable.js:37:25)
at Observable.js:31:30
at errorContext (errorContext.js:19:9)
at Observable.subscribe (Observable.js:22:21)

And on the network tab, I can see that the GET is not executed so it looks as though HttpClient is failing before then.

What am I doing wrong?

The file exists and I can see it using Postman or even the browser (but the request isn't even executing).


Solution

  • The code for creating the request looks fine. The stack trace of the error points to the creation of the request headers, however you have not added any additional headers to this request.

    So there must be something else in your app which messes with the request and somehow makes the headers invalid. Usually this happens in interceptors. To find the interceptors in your app, search for the HTTP_INTERCEPTORS injection token or the withInterceptors function.

    After you found the interceptors, you can remove them temporarily one by one to see which one causes the issues. Finally, you can fix the interceptor's logic.