【问题标题】:Iterating an interface array with `forEach()`使用 `forEach()` 迭代接口数组
【发布时间】:2021-05-12 12:14:55
【问题描述】:

我是 Typescript 的新手,我想将 HTTP GET 的响应保存到由接口定义的类型的数组中。

getErrors() {
  return this.http.get<ErrorsInterface[]>(environment.apiUrl+'errors').toPromise()
}

然后我这样声明数组并调用函数getErrors()

errorsData: ErrorsInterface[]= []

this.errorsData = await this.ErrorsService.getErrors()
this.errorsData.forEach(res => {
 console.log(res.number)
})

但我收到以下错误:

错误错误:未捕获(承诺中):TypeError:this.errorsData.forEach 不是函数 TypeError: this.errorsData.forEach 不是函数

感谢您的帮助

【问题讨论】:

    标签: angular typescript interface


    【解决方案1】:

    我认为这里不需要将 observable 转换为 Promise。你可以只使用可观察的

    服务

    getErrors(): Observable<any> {  // <-- return observable
      return this.http.get<ErrorsInterface[]>(environment.apiUrl+'errors');
    }
    

    组件

    errorsData: ErrorsInterface[]= []
    
    this.ErrorsService.getErrors().subscribe({
      next: (res: any) => {
        this.errorsData = res;
        this.errorsData.forEach(error => {
          console.log(error.number)
        });
      }
      error: (error: any) => {
        // handle error
      }
    );
    

    注意:

    1. 您无法将异步获取转换为同步获取。任何依赖异步数据的语句(如forEach必须在订阅中。更多关于异步数据的信息here

    2. toPromise() 在 RxJS 7 中是 being deprecated 并且可能在 RxJS 中消失了

    【讨论】:

    • 谢谢,我也错过了 this.errorsData = res.errors;
    【解决方案2】:

    //in your service file
    
    getErrors():Observable<ErrorInterface[]> {
          return this.http.get<ErrorsInterface[]>(environment.apiUrl+'errors')
      }

     private errorsData= []
    
    
    getErrors(){
    this.ErrorsService.getErrors().Subscribe(res=> 
    this.errorsData=res
    )
    //console.log(this.errorsData.length)
    }

    【讨论】:

    • 为什么要删除组件中的类型定义? errorsData: ErrorsInterface[]= []?
    猜你喜欢
    • 2013-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 2015-06-06
    • 1970-01-01
    • 2021-09-14
    • 2012-11-29
    相关资源
    最近更新 更多