首页 > 解决方案 > TS2339:“对象”类型上不存在属性“地图”

问题描述

我有以下代码:

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

标签: angulartypescriptionic-frameworkionic3

解决方案


您没有在 Angular 中告诉getAngular,您正在接收什么类型的数据,因此 Angular 会自动假定它是一个匿名对象,因为 Angular httpclient 会将数据解析为. 还有一些不相关的东西,因为您使用的是 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))
    )
}

推荐阅读