angular - “对象”类型上不存在属性“地图”
问题描述
我最近接触了 Angular 和 TypeScript 并试图学习一些东西并找到了一个我可以尝试的特定项目(如果有人想查看该项目,我可以在链接中编辑)(尝试从 pokemon api 读取 json 数据)
此行中的“对象”类型上不存在属性“地图”。
.then(items => items.map((item, idx) =>
这是完整的代码
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class PokedexService {
private baseUrl: string = 'https://pokeapi.co/api/v2/pokemon/';
private baseSpriteUrl: string = 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/';
constructor(private http: HttpClient) { }
getPokemon(offset: number, limit: number) {
return this.http.get(`${this.baseUrl}?offset=${offset}&limit=${limit}`)
.toPromise()
//.then(response => response.json().results)
//.map((results = > response.json()))
.then(items => items.map((item, idx) => {
const id: number = idx + offset + 1;
return {
name: item.name,
sprite: `${this.baseSpriteUrl}${id}.png`,
id
};
}));
}
}
当我尝试运行该项目时,我首先收到此脚本的 json 部分(对象上不存在 json)的错误,然后我了解到使用新的更新您不需要这些行,因此我将它们注释掉。(不知道是对是错)然后我得到了我现在要问的错误。
我希望我没有做错什么,并等待任何指导。同样,我是这个领域的新手,但知道编码。
解决方案
如果您将声明返回值(即 Items[]),您将能够运行 .map 我通常将 API 服务和组件分开,所以它看起来像这样:
api.service.ts
public GetPokemon(): Observable<Items[]> {
const url = this.url_to_backend_method;
return this.http.get<Items[]>(url)
.pipe(catchError(this.handleError));
}
组件.ts
private getPokemon() {
this.api.GetPokemon().subscribe(
items => items.map((item, idx) => {
** run your logic here **};
}, error => {
** deal with error here **
});
}
希望这可以帮助
推荐阅读
- sockets - 如何通过客户端的socketDataArrived方法正确接收数据
- c - 迭代存储在堆上的数组
- c++ - 如何在 C++ 中对包含自定义对象的容器使用分区函数
- swift - Xcode 编译错误“错误中止陷阱 6”
- typescript - Angular 7 每隔一段时间从 API 轮询/获取响应代码
- python - Pycharm 和 python 命令行输出在运行 unittest 时显示不同的结果
- eclipse - 有一种方法可以为 IFolders 之类的 IResources 执行 PRE_DELETE 事件吗?
- android - 通过蓝牙向安卓发送字符串
- java - 加入 Kafka Streams 时如何访问原始记录
- python-3.x - Firefox Selenium (python) 不会打开 WebRTC 流