【问题标题】:Angular HttpClient get method subscribe Cannot read property 'length' of undefinedAngular HttpClient 获取方法订阅无法读取未定义的属性“长度”
【发布时间】:2019-07-21 09:09:40
【问题描述】:

我正在尝试通过使用httpclient的get方法来确定文件是否存在。

然后根据结果是否存在文件调用具有不同参数的一种方法。

 public faviconLogic(iconName: string): void {
    this.getFile(`assets/favicon/${iconName}/favicon.ico`)
    .subscribe(
      () => this.setFavicon(iconName),
      () => this.setFavicon('default')
    );
  }

  private getFile(filename: string): Observable<Blob> {
    return this.http.get(filename, { responseType: 'blob' });
  }

输入方法 faviconlogic 时出现错误

TypeError: Cannot read property 'length' of undefined
    at t.applyUpdate

我尝试添加标题 - 没有。调用方法 getFile 本身可以正常工作,因为订阅返回的 Observable。我做错了什么?

【问题讨论】:

  • applyUpdate 是您的代码但未包含在您的问题中吗?你在某个地方给length打电话吗?
  • 不,我没有在任何地方调用 applyUpdate,也没有调用长度。 applyUpdate 应该是来自 HttpHeaders 的方法。
  • 在这种情况下,我们需要一个堆栈闪电战来重现您的错误......
  • @Morlas 你能分享adding headers 的代码吗?该错误表明您正在为标题设置undefined
  • @Vadi public getFile(filename: string, contentType: string): Observable&lt;any&gt; { return this.http.get(filename, { headers: new HttpHeaders({ 'Content-Type': 'image/x-icon' }) }); }

标签: angular observable subscription angular-httpclient


【解决方案1】:

好的,问题出在 Http Headers 中的授权令牌上。

【讨论】:

  • 你能解释一下发生了什么吗?我遇到了同样的问题
  • 你有设置拦截器吗?可能有一个 http get 接受的文件类型列表,而您缺少文件类型声明
猜你喜欢
  • 2019-09-14
  • 1970-01-01
  • 1970-01-01
  • 2018-02-13
  • 2019-10-11
  • 1970-01-01
  • 1970-01-01
  • 2021-11-23
  • 1970-01-01
相关资源
最近更新 更多