【问题标题】:Angular - Type '{}' is missing the following properties from type 'any[]'Angular - 类型“{}”缺少类型“任何 []”中的以下属性
【发布时间】:2021-03-24 17:48:00
【问题描述】:

在我的 Angular 项目中,我收到此错误:Type '{}' is missing the following properties from type 'any[]'

我有一个简单的角度代码,其中有一个帮助类向 url 发出请求,它发送回一个像 [ {a: b, c: d}, {e: f} ... ] 这样的 JSON 数组,一切正常,具有预期的结果,但是当我尝试将结果返回到主页。

我会继续强制执行该类型,但不知道我可能需要什么来解决此错误并想了解它。

我愿意接受有关代码的问题。


帮助类

export class ExampleJsonGetter{
  constructor(private http: HttpClient) {
  }

  getArray() {
    return new Promise((resolve, reject) => {
      this.http.post<any>('https://anUrl.com/getjsonarray')
        .subscribe({
          next: data => {
            resolve(data);
          },
          error: error => {
            reject(error);
          }
        });
    });
  }
}

主页类

export class MainPage{
  variable = [];
  constructor(){
    example.getArray().then((data)=>{
/*★*/ variable = data;  /* ★ */
      console.log(variable); // on firefox: 'Array(12): ...' As expected
      console.log(typeof variable); // 'object', souldn't it be Array?
    }).catch(e=>console.error(e));
  }
}

似乎起作用的唯一方法是将替换为variable = new Array( ...data);

我什至不知道那些三点是做什么的,你能解释一下吗?

【问题讨论】:

标签: javascript angular typescript


【解决方案1】:

这是一个typescript 错误,表示类型不匹配。让我们在下面考虑

getArray() {
    return new Promise((resolve, reject) => {
      this.http.post<any>('https://anUrl.com/getjsonarray')
        .subscribe({
          next: data => {
            resolve(data);
          },
          error: error => {
            reject(error);
          }
        });
    });
  }

getArray() 将返回Promise&lt;any&gt;,因为this.http.post&lt;any&gt;('https://anUrl.com/getjsonarray') 行返回any

在主页中有variable = [];,表示类型any[]。因此,您尝试将类型 any 分配给类型 any[],这将引发错误。

要解决此问题,请将行更改为 this.http.post&lt;any[]&gt;('https://anUrl.com/getjsonarray')

【讨论】:

  • 谢谢,你能给我链接或说出fun&lt;something&gt;(args)带尖括号的sintax是什么吗?
  • 这是使用 运算符的类型转换,this.http.get&lt;any[]&gt;(url) 意味着 get 函数将返回 any[]
  • thans,我发现这个正在寻找类型转换,我将它链接在这里以供将来使用:stackoverflow.com/questions/37358364/…
  • 我刚刚应用了您的更正,很遗憾它不起作用,我该怎么办?
  • 是的。 data.forEach() 有效,所以我尝试将值推送到一个数组中,该数组一旦记录下来似乎是未定义的(抛出错误)。也许问题不仅仅是数据本身,而是我的语法错误。建议?同时我将阅读更多关于如何使用 arays here: Typescript Spec on githubHere: typescript microsoft handbook
【解决方案2】:

最好使用SubscriptionPromise,而不是在单个http 调用中组合它们。

助手

import { throwError, Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';


export class ExampleJsonGetter {
   ...
   getArray(): Observable<any> {
     return this.http
       .post<any>('https://anUrl.com/getjsonarray')
       .pipe(catchError(err => throwError(err)))              // Catch and throw error

   }
}

如果上述端点发送的是 object 而不是 array,您可以通过将其添加到管道中来将响应转换为数组

import { toArray } from 'rxjs/operators';
getArray(): Observable<any[]> {                   // Now in any[] type
  return this.http
     .post<any>('https://anUrl.com/getjsonarray')
     .pipe(
       toArray(),                                // Add this
       catchError(err => throwError(err))
     )             
}

主页

example
  .getArray()
  .subscribe(
    data => console.log(data, Array.isArray(data))      // Check the data and confirm if it's an array
    err => console.error(err)                           // Console any error if there's any

  )       

【讨论】:

  • 这种管道是我见过但从未使用过的东西。我应该寻找哪个主题来了解它?我只是想学习观察者和 rxjs 可观察对象,但由于我只有一个订阅,我认为承诺会做得更好。 (我只知道承诺处理异步,现在很紧)
  • 哦,我明白了,没问题 :) 管道与使用 rxjs 处理可观察对象有关。您可以在此处了解更多信息:learnrxjs.io 如果这对您来说是新事物,那么现在诉诸承诺没有问题,那也可以:)
猜你喜欢
  • 2023-03-11
  • 2021-04-20
  • 2021-07-29
  • 1970-01-01
  • 2020-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-11
相关资源
最近更新 更多