Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular TypeError: Cannot read property 'length' of null in Promise subscribe()

Tags:

angular

I am calling an API endpoint and receiving an error back but I can not view the error when using console.log because I get error below. Is there another way to get the error?

ERROR

TypeError: Cannot read property 'length' of null
    at http.js:109
    at Array.forEach (<anonymous>)
    at HttpHeaders.lazyInit (http.js:103)
    at HttpHeaders.init (http.js:251)
    at HttpHeaders.forEach (http.js:354)
    at Observable._subscribe (http.js:2153)
    at Observable._trySubscribe (Observable.js:172)
    at Observable.subscribe (Observable.js:160)
    at Object.subscribeToResult (subscribeToResult.js:23)
    at MergeMapSubscriber._innerSub (mergeMap.js:132)

PROVIDER

    import { HttpClient } from '@angular/common/http';
    import { Http, Headers , RequestOptions } from '@angular/http';
    import { Injectable } from '@angular/core';

    @Injectable()
    export class GamesProvider {

    // API url 
    apiUrl = 'http://xxxxx.com/api';

    headers : any;
    options: any;

    this.headers =  new Headers();
    this.headers.append('Accept', 'application/json');
    this.headers.append('Content-Type', 'application/json' );

    this.headers.append('Authorization', 'Bearer' + this.token);

    this.options = new RequestOptions({headers: this.headers});

    getUsers(ex) {
      return new Promise(resolve => {
       this.http.get(this.apiUrl+'/api/online/'+ex, {headers: this.options}).subscribe(data => {
        resolve(data);
       }, err => {
        console.log(err);
       }).catch((err) => {

                // Do messaging and error handling here

                return Observable.throw(err)
            });
     });
    }
like image 459
condo1234 Avatar asked May 07 '18 12:05

condo1234


2 Answers

The cause of this error is that you are adding a header to you http request that has a value of null. You aren't doing it in your provided code, so chances are that this happens in your http interceptor.

It could very easily happen if your http interceptor adds a token to every http request, even if a value for the token has not been set, or if the interceptor is not properly accessing the token variable.

like image 134
Joakim Avatar answered Nov 15 '22 10:11

Joakim


This happens when any of the value in headers is null or undefined.

For example:

{ headers: this.options }

If this.options is something like:

{ token : null }

You will get the error mentioned in this question.
You won't even see a request being generated by angular http in this case.

like image 37
Sumit Chauhan Avatar answered Nov 15 '22 10:11

Sumit Chauhan