Ionic2 并得到 Json

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 进行测试 purpose.I 得到了错误:

GET http://localhost:8100/app/Ressources/slides.json 404 (Not Found)

我不明白为什么。而且我找不到简单且最新的教程。还是应该使用 fetch()?

只需尝试在 GetItems() 方法中获取 response.json() 而不是 response.json().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;
});

编辑: 将其放入 class 也可能会有所帮助

export class MyClass{
    static get parameters(){
        return [[Http]];
    }
}

首先将你的json复制到以下目录(你可以创建文件夹"data"):

[appname]/www/data/data.json

在您的控制台中输入以下命令:

ionic g provider JsonData

它应该为该页面的 you.Go 创建一个提供程序,并在 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);
          });
      });
  }

问题是因为 json 文件在本地浏览器(计算机)和设备(android)中的路径不同。在 src\assets 文件夹中创建 data 文件夹。将您的 json 文件移动到其中。

当我们 运行 ionic serve 时,它会将该文件夹(包含文件)移动到 www\assets 文件夹中。然后做以下事情:

  1. 导入 Platform 服务 ionic2

     import { Platform } from 'ionic-angular';
    


  1. 注入 Platform 服务。

      constructor(private http: Http, private platform: Platform ) { }
    


  1. 使用 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()
            });
    }