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

问题描述

我最近接触了 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)的错误,然后我了解到使用新的更新您不需要这些行,因此我将它们注释掉。(不知道是对是错)然后我得到了我现在要问的错误。

我希望我没有做错什么,并等待任何指导。同样,我是这个领域的新手,但知道编码。

标签: angulartypescript

解决方案


如果您将声明返回值(即 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 **
            });
    }

希望这可以帮助


推荐阅读