Angular TypeError:无法读取属性'长度'在Promise中的null订阅()

时间:2018-05-07 12:08:48

标签: angular

我正在调用API端点并收到错误但我在使用console.log时无法查看错误,因为我收到以下错误。还有另一种方法可以解决错误吗?

错误

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

2 个答案:

答案 0 :(得分:7)

此错误的原因是您向http请求添加了一个值为OneToMany的标头。您没有在提供的代码中执行此操作,因此很有可能会在您的http拦截器中发生这种情况。

如果你的http拦截器向每个 http请求添加一个令牌,即使没有设置令牌的值,或者拦截器没有正确访问令牌变量,也很容易发生

答案 1 :(得分:1)

当标头中的任何值为nullundefined时,就会发生这种情况。

例如:

{ headers: this.options }

如果this.options类似于:

{ token : null }

您将收到此问题中提到的错误。
在这种情况下,您甚至都不会看到由角度http生成的请求。

相关问题