TS2339: 属性 'map' 在类型 'Object' 上不存在

TS2339: Property 'map' does not exist on type 'Object'

我有以下代码:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import { map } from 'rxjs/operators';

interface SingleParamConstructor<T> {
  new (response: any): T;
  id: T;
}

@Injectable()
export class RestProvider<T> {
  baseUrl:string = "http://localhost:3000";

  constructor(private ctor: SingleParamConstructor<T>, private httpClient : HttpClient) { }

  public getEntities<T>(): Observable<T[]> {
    return this.httpClient
      .get(this.baseUrl + '/products')
      .pipe(map(entities => {
        return entities.map((entity) => new this.ctor(entity));
      }))
      .catch((err) => Observable.throw(err));

  }
}

当我尝试上面的代码时,我得到 TS2339: Property 'map' does not exist on type 'Object'.

负责的行是:return entities.map((entity) => new this.ctor(entity));

我哪里做错了,我该如何映射 entities

我几乎可以肯定你得到的 (entities) 是一个对象,它是不可迭代的。

pipe(map 更改为 pipe(tap 并执行 console.log 以查看您从服务器获得的内容,

.pipe(tap(entities => console.log(entities));

然后如果你需要遍历对象的道具,做一个 Object.keys(myObj) 其中 returns 一个数组。

希望对你有帮助

您没有在 get 中告诉 angular 您正在接收什么类型的数据,因此 Angular 自动假定它是 an anonymous object, as that is what Angular httpclient parses to the data to。还有一些不相关的东西,因为你使用的是 rxjs 6 -> 使用 catchError 而不是 .catch:

import { catchError, map } from 'rxjs/operators';
import { of } from 'rxjs';

// ...

public getEntities<T>(): Observable<T[]> {
  return this.httpClient
    // note below, now angular knows it's an array!
    .get<T[]>(this.baseUrl + '/products')
    .pipe(
       map(entities => {
        return entities.map((entity) => new this.ctor(entity));
       }),
       catchError((err) => of(err))
    )
}