【发布时间】:2018-05-22 19:31:27
【问题描述】:
我正在尝试使用 Ionic 打字稿向我的本地 JSON 文件发出请求,并检索我的 JSON 文件中的所有游戏对象。这是我目前所拥有的:
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() 函数时,我得到的结果如下所示:
operator
:CatchOperator {caught: Observable, selector: ƒ}
source
:Observable {_isScalar: false, source: Observable, operator: MapOperator}
_isScalar
:false
__proto__
:Object
我期待的是一个可观察的游戏对象数组。
Game.ts:
export class Game {
gameid: number
genres: string
images: string
name: string
developer: string
publisher: string
date: string
description: string
players: number
}
这是我的 JSON 文件的样子:
{
"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
},
...
...
...
]
}
【问题讨论】:
标签: json ionic-framework rxjs http-get