[英]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.