【问题标题】:Angular TypeError: Cannot read property 'length' of null in Promise subscribe()Angular TypeError:无法在 Promise subscribe() 中读取 null 的属性“长度”
【发布时间】:2019-01-13 04:17:03
【问题描述】:

我正在调用 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)

提供者

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

【问题讨论】:

  • 你在哪里使用长度?我认为您错过了使用长度属性的部分
  • 我不使用它...
  • 这是一个函数吗?你能展示更多你的代码吗?
  • 是的,它是 1 个函数的全部代码
  • return new Promise((resolve,reject) =&gt; and reject(err); inside your catch 或 err=&gt;{ reject(err);} 我不确定它是否会给出相同的结果

标签: angular


【解决方案1】:

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

如果您的 http 拦截器向 每个 http 请求添加一个令牌,即使尚未设置令牌的值,或者如果拦截器未正确访问令牌变量,也很容易发生这种情况.

【讨论】:

  • 对我的问题来说确实如此。似乎headers.set 中当前存在问题,因为它不会用现有键替换标头的值,而只是作为headers.append 工作。给我留下两个具有相同键的标题,一个具有空值,第二个具有新的 set 值。
【解决方案2】:

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

例如:

{ headers: this.options }

如果this.options 类似于:

{ token : null }

你会得到这个问题中提到的错误。
在这种情况下,您甚至不会看到 angular http 生成的请求。

【讨论】:

    猜你喜欢
    • 2018-03-27
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 1970-01-01
    相关资源
    最近更新 更多