错误TS2322:类型'Observable <{} []>'无法分配给类型'Observable <archive [] []>'

时间:2019-05-13 22:35:46

标签: angular typescript

我正在将更新从Angular 5.2.11推送到7.3.9。我遇到的类型问题在以前的Angular版本中似乎不是问题。

修复了forkJoin的导入后,以下代码失败,并出现以下错误:

ERROR in src/app/reports/report-measurements-options/report-measurements-options.component.ts(377,5): error TS2322: Type 'Observable<{}[]>' is not assignable to type 'Observabl
e<Archive[][]>'.
  Type '{}[]' is not assignable to type 'Archive[][]'.
    Type '{}' is missing the following properties from type 'Archive[]': length, pop, push, concat, and 26 more.
getArchives(): Observable<Archive[][]> {
    if ((this.startDate) > (this.endDate)) {
      let temp = this.startDate;
      this.startDate = this.endDate;
      this.endDate = temp;
    }

    let observableBatch: any[] = [];

    this.selectedBins.forEach(bin => {
      const definition = bin.definitions.find(d => d.type === this.selectedReadingType);

      bin.selectedDefinition = definition;
      bin.definitionUnits = definition.units;

      observableBatch.push(this.archiveService.listArchives(definition.id, this.startDate, this.endDate)
        .map((res: Archive[]) => res));
    });

    return forkJoin(observableBatch);
  }

我希望该方法返回正确的类型并像更新前一样返回。

2 个答案:

答案 0 :(得分:0)

我认为问题出在此指令中

this.archiveService.listArchives(definition.id, this.startDate, this.endDate)
        .map((res: Archive[]) => res)

您可以删除.map((res:Archive [])=> res),因为您将返回相同的对象,否则将Angle从5升级到7,因此rxjs也已升级,要解决此问题,您应该使用管道带有这样的地图:

this.archiveService.listArchives(definition.id, this.startDate, this.endDate)
            .pipe(map((res: Archive[]) => res))

答案 1 :(得分:0)

我不得不在使用管道的同时删除方法的类型声明。现在,以下代码可以正常编译:

getArchives() /*removed type*/{
    if ((this.startDate) > (this.endDate)) {
      let temp = this.startDate;
      this.startDate = this.endDate;
      this.endDate = temp;
    }

    let observableBatch: any[] = [];

    this.selectedBins.forEach(bin => {
      const definition = bin.definitions.find(d => d.type === this.selectedReadingType);

      bin.selectedDefinition = definition;
      bin.definitionUnits = definition.units;

      observableBatch.push(this.archiveService.listArchives(definition.id, this.startDate, this.endDate)
        .pipe(map((res: Archive[]) => res)));
    });

    return forkJoin(observableBatch);
  }