Ionic2并得到Json [英] Ionic2 and get Json
本文介绍了Ionic2并得到Json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用Ionic2,我提供了一个服务来获取本地存储的Json。
I am trying to use Ionic2 and I made a service to fetch a local stored Json.
import {Injectable} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';
@Injectable()
export class Page1Service {
public constructor(private _http: Http) {}
public GetItems() {
return this._http.get('/app/Ressources/Items.json').map((response: Response) => response.json().data);
}
public PrintJson():boolean {
var myresult;
this.GetItems().subscribe((result) => {
myresult = result;
console.log(result);
});
}
我还制作了PrintJson()方法,只需打印json用于测试目的。我收到错误:
I also a made PrintJson() method that just print the json for test purpose.I got the error:
GET http://localhost:8100/app/Ressources/slides.json 404 (Not Found)
我不明白为什么。我找不到一个简单易用的教程。或者我应该使用fetch()?
I don't get why. And I can't find an easy and uptodate tutorial. Or should I use fetch()?
推荐答案
首先将你的json复制到以下目录(你可以创建文件夹data ):
First copy your json to the following dir(you can create the folder "data"):
[appname]/www/data/data.json
在控制台中输入以下命令:
Type in the following command in your console:
ionic g provider JsonData
它应该为您创建一个提供者。转到该页面并在 load()
function:
It should create a provider for you.Go to that page and enter the following in load()
function:
load() {
if (this.data) {
// already loaded data
return Promise.resolve(this.data);
}
// don't have the data yet
return new Promise(resolve => {
// We're using Angular Http provider to request the data,
// then on the response it'll map the JSON data to a parsed JS object.
// Next we process the data and resolve the promise with the new data.
this.http.get('data/data.json').subscribe(res => {
// we've got back the raw data, now generate the core schedule data
// and save the data for later reference
this.data = res.json();
resolve(this.data);
console.log(this.data);
});
});
}
这篇关于Ionic2并得到Json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文