首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用rxjs在本地json文件上创建HTTP get()?

如何使用rxjs在本地json文件上创建HTTP get()?
EN

Stack Overflow用户
提问于 2017-12-08 22:25:03
回答 3查看 1.5K关注 0票数 0

我正在尝试使用Ionic typescript向本地JSON文件发出请求,并检索JSON文件中的所有游戏对象。这是我到目前为止所知道的:

代码语言:javascript
复制
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators/map';
import { catchError } from 'rxjs/operators/catchError';
import { Observable } from "rxjs/Observable";
import { Game } from "../../models/Game";

import { Http, Response, RequestOptions, Headers } from '@angular/http';

/*
  Generated class for the GamesProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class GamesProvider {
  constructor(public http: HttpClient) {

  }

  public getGames(): Observable<Array<Game>> {

      return this.http.get('/assets/games.json').pipe(
        map((res: Response) => res.json().games),
        catchError(this.handleError)
      );
  }

  public handleError(error: any) {
      // log error
      // could be something more sofisticated
      let errorMsg = error.message || `Yikes! There was a problem with our hyperdrive device and we couldn't retrieve your data!`
      console.error(errorMsg);

      // throw an application level error
      return Observable.throw(errorMsg);
  }
}

当我调用getGames()函数时,我得到了如下所示的结果:

代码语言:javascript
复制
operator
    :CatchOperator {caught: Observable, selector: ƒ}
    source
    :Observable {_isScalar: false, source: Observable, operator: MapOperator}
    _isScalar
    :false
    __proto__
    :Object

我所期望的是一个可观察到的游戏对象数组。

Game.ts:

代码语言:javascript
复制
export class Game {
    gameid: number
    genres: string
    images: string
    name: string
    developer: string
    publisher: string
    date: string
    description: string
    players: number
}

这是我的JSON文件的样子:

代码语言:javascript
复制
{
    "games":[
  {
    "Id": 1,
    "name": "007: GoldenEye",
    "genres": "Action/First-Person Shooter",
    "date": "25-Aug-97",
    "images": "007: GoldenEye.png",
    "developer": "Rare",
    "publisher": "Nintendo",
    "description": "A video game released for the Nintendo 64.",
    "players": 4
  },
  {
    "Id": 2,
    "name": "007: The World Is Not Enough",
    "genres": "Action/First-Person Shooter",
    "date": "1-Nov-00",
    "images": "007: The World Is Not Enough.png",
    "developer": "Eurocom",
    "publisher": "Electronic Arts",
    "description": "A video game released for the Nintendo 64.",
    "players": 4
  },
...
...
...
 ]
}
EN

回答 3

Stack Overflow用户

发布于 2017-12-08 23:56:48

如果您使用HttpClient,则不应该使用json();HttpClient上的get()方法使访问此数据变得简单:

代码语言:javascript
复制
ngOnInit(): void {
    this.http.get('/assets/games.json').subscribe(data => {
      this.games = data.games;
    },
    (err: HttpErrorResponse) => {
        if (err.error instanceof Error) {
            console.log('An error occurred:', err.error.message);
        } else {
            console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
        }
    })
}

然后你可以使用:

代码语言:javascript
复制
<div *ngFor="let game of games">{{game | json}}</div>
票数 2
EN

Stack Overflow用户

发布于 2017-12-08 22:29:26

我相信你需要的不是管道,而是map (去掉管道)

代码语言:javascript
复制
return this.http.get('/assets/games.json').map(
(res: Response) => res.json().games).catch(this.handleError);

查看文档:https://angular.io/guide/http您也可以使用subscribe进行订阅

票数 1
EN

Stack Overflow用户

发布于 2017-12-09 01:16:46

如果您的Game类更改为

代码语言:javascript
复制
export class Game {
    id: number
    genres: string
    images: string
    name: string
    developer: string
    publisher: string
    date: string
    description: string
    players: number
}

您可以将http.get的输出转换为您的游戏类:

代码语言:javascript
复制
return this.http.get('/assets/games.json').map(
(res: Response) => <Game>res.json().games).catch(this.handleError);

为了处理错误,可以使用此方法

代码语言:javascript
复制
protected handleError(error: any): Observable<any> {
    console.log(error.message || error);
    const response = 'some error occurred!';
    return Observable.of(response);
  }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47716290

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档