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

Discussão em 'Angular' iniciado por Rob Mousley, Novembro 21, 2024.

  1. Rob Mousley

    Rob Mousley Guest

    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 comprises: { "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).

    Continue reading...

Compartilhe esta Página