angular - 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
?
解决方案
您没有在 Angular 中告诉get
Angular,您正在接收什么类型的数据,因此 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))
)
}
推荐阅读
- discord.js - Discord.js How would I create a bot status announcement?
- javascript - Evaluating chess game state using Fairy Stockfish and Node
- google-cloud-platform - 以编程方式获取 GCP 上的当前服务帐户
- matlab - cftool 不适合自定义拟合
- asp.net-core - How can I remove slash in route of controller?
- ios - how to select xcode version in fastlane when using github actions
- python - Smoothening a curve in Python
- ios - iOS Notification Extension to load media not called
- javascript - 跨浏览器扩展后台脚本导入错误
- android - WebView init 出现异常:无法创建锁定文件 webview_data.lock EACCES(权限被拒绝)