【问题标题】:Property 'filter' does not exist on type 'Object'“对象”类型上不存在属性“过滤器”
【发布时间】:2018-08-02 16:00:57
【问题描述】:

将我的代码更新为 HttpClient 后,我​​无法让 filter() 处理响应。我不断收到“对象”类型上不存在属性“过滤器”:

TS:

liqOnChange(selection): void  {
        this.http.get(this.json_liq).subscribe(res => {
            this.arr = res.filter(
                res => res.id == selection.target.value);
        });
}

【问题讨论】:

  • Filter 是一个数组方法。 res 是数组吗?

标签: javascript angular httpclient


【解决方案1】:

filter 是一种数组方法,在您的情况下不能用于对象res。

首先检查res是否是一个数组。

if(Array.isArray(res)){
   this.arr = res.filter(
                res => res.id == selection.target.value);
}

或者将类型设置为res as (res: Array<any>)

如果你的 api 返回一个对象,在大多数情况下应该是,你不能在这里使用filter 方法,你应该将它用于res 对象内的数组。

【讨论】:

  • 问题来自 API,感谢您指出这一点。我确信我得到了一个数组,但是在像你说的那样检查并将类型设置为数组但没有成功之后,我意识到我得到了一个里面有一个数组的对象。
  • @prevox 没问题
【解决方案2】:

我认为您的 res 不是数组,请检查 res 的类型,如果是数组,则过滤方法有效。

【讨论】:

    【解决方案3】:

    对象为空或不是数组
    尝试检查对象是否不为 null 并且是带有
    if(res != null && Array.isArray(res))

    的数组

    【讨论】:

      【解决方案4】:

      改变这一行:

      this.http.get(this.json_liq).subscribe(res => {
      

      到这里:

      this.http.get(this.json_liq).subscribe((res: any) => {
      

      或者更好的是:

       this.http.get(this.json_liq).subscribe((res: Array<any>) => {
      

      并且您应该能够绕过编译器的类型检查错误。

      以下是来自official docs 的更多信息:

      any 类型是处理现有 JavaScript 的强大方式, 允许您在期间逐渐选择加入和退出类型检查 汇编。您可能希望 Object 扮演类似的角色,因为它 用其他语言做。但是 Object 类型的变量只允许你 为它们分配任何值 - 你不能调用任意方法 它们,甚至是实际存在的:

      let notSure: any = 4;
      notSure.ifItExists(); // okay, ifItExists might exist at runtime
      notSure.toFixed(); // okay, toFixed exists (but the compiler doesn't check)
      
      let prettySure: Object = 4;
      prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'.
      

      【讨论】:

        猜你喜欢
        • 2021-08-11
        • 1970-01-01
        • 2019-04-24
        • 2017-05-23
        • 2020-02-15
        • 2019-08-27
        • 1970-01-01
        • 1970-01-01
        • 2018-12-11
        相关资源
        最近更新 更多