代码之家  ›  专栏  ›  技术社区  ›  Drago

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

  •  0
  • Drago  · 技术社区  · 6 年前

    我有以下代码:

    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 ?

    1 回复  |  直到 6 年前
        1
  •  2
  •   AT82    6 年前

    你不是在讲故事 get ,所以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))
        )
    }
    
        2
  •  1
  •   Francisco Santorelli    6 年前

    我几乎可以肯定( entities

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

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

    希望这对你有帮助

    推荐文章