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

时间:2017-12-08 14:25:03

标签: json ionic-framework rxjs http-get

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

function deleteToDo() {
   var index = prompt("Enter index of todo to delete");

   if (index >= 0 && index < todos.length) {
       var deletedItem = todos[index];
       todos.splice(index, 1);
       console.log(deletedItem);
   }
}

当我调用getGames()函数时,我得到一个看起来像这样的结果:

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);
  }
}

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

Game.ts:

operator
    :CatchOperator {caught: Observable, selector: ƒ}
    source
    :Observable {_isScalar: false, source: Observable, operator: MapOperator}
    _isScalar
    :false
    __proto__
    :Object

这就是我的JSON文件:

export class Game {
    gameid: number
    genres: string
    images: string
    name: string
    developer: string
    publisher: string
    date: string
    description: string
    players: number
}

3 个答案:

答案 0 :(得分:2)

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

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}`);
        }
    })
}

然后你可以使用:

<div *ngFor="let game of games">{{game | json}}</div>

答案 1 :(得分:1)

我相信你需要地图而不是管道(并且只是摆脱管道)

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

检查文档:https://angular.io/guide/http您也可以使用订阅

执行此操作

答案 2 :(得分:1)

如果您的游戏类改为

export class Game {
    id: number
    genres: string
    images: string
    name: string
    developer: string
    publisher: string
    date: string
    description: string
    players: number
}

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

return this.http.get('/assets/games.json').map(
(res: Response) => <Game>res.json().games).catch(this.handleError);

处理错误可以使用此方法

protected handleError(error: any): Observable<any> {
    console.log(error.message || error);
    const response = 'some error occurred!';
    return Observable.of(response);
  }