我有以下代码:
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
?
答案 0 :(得分:2)
您没有在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))
)
}
答案 1 :(得分:1)
我几乎可以确定您得到的(entities
)是一个不可迭代的对象。
将pipe(map
更改为pipe(tap
并执行console.log,以查看从服务器获取的内容,
.pipe(tap(entities => console.log(entities));
然后,如果您需要遍历对象的道具,请执行Object.keys(myObj)来返回数组。
希望这对您有帮助