[英]Ionic2 and get Json
我正在尝试使用Ionic2,并且提供了一项服务来获取本地存储的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以供测试之用。
GET http://localhost:8100/app/Ressources/slides.json 404 (Not Found)
我不明白为什么。 而且我找不到简单且最新的教程。 还是应该使用fetch()?
首先将您的json复制到以下目录(您可以创建文件夹“ data”):
[appname]/www/data/data.json
在控制台中键入以下命令:
ionic g provider JsonData
它应该为您创建一个提供程序。转到该页面并在load()
函数中输入以下内容:
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);
});
});
}
我通常会像这样在api调用周围创建一个Observable:
public GetItems() {
return Observable.create(observer => {
this._http.get('/app/Ressources/Items.json').map(res =>res.json()).subscribe(data=>{
observer.next(data)
observer.complete();
});
});
}
然后,我必须订阅该方法才能获得结果并对其进行处理。 (您可以将结果委托给GUI中的列表)
GetItems().subscribe(data=>{
myResult = data;
});
编辑:这可能也有助于将其放在类中
export class MyClass{
static get parameters(){
return [[Http]];
}
}
只需尝试获取GetItems()方法中的response.json()而不是response.json()。data
问题是由于本地浏览器(计算机)和设备(android)中json文件的路径不同。 在src\\assets
文件夹内创建data
文件夹。 将您的json文件移到其中。
当我们运行ionic serve
,它将将该文件夹(带有文件)移动到www\\assets
文件夹中。 然后执行以下操作:
ionic2
导入Platform
服务
import { Platform } from 'ionic-angular';
注入Platform
服务。
constructor(private http: Http, private platform: Platform ) { }
使用Platform
服务。
public getItems() { var url = 'assets/data/Items.json'; if (this.platform.is('cordova') && this.platform.is('android')) { url = "/android_asset/www/" + url; } return this.http.get(url) .map((res) => { return res.json() }); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.