2017-09-02 125 views
0

Ionic在通過HTTP從JSON文件獲取數據時遇到問題,我不知道錯誤是什麼問題,這很奇怪。在Ionic 3中使用Http獲取JSON數據

error message in chrome devtool

這裏是代碼:

src/pages/subhome/line/line.ts(該Subhome包含的頁面的幾個文件夾)

import { Component } from '@angular/core'; 
 
import { IonicPage, NavController, NavParams } from 'ionic-angular'; 
 
import { Http } from '@angular/http'; 
 
import 'rxjs/add/operator/map'; 
 
/** 
 
* Generated class for the LinePage page. 
 
* 
 
* See http://ionicframework.com/docs/components/#navigation for more info 
 
* on Ionic pages and navigation. 
 
*/ 
 

 
@IonicPage() 
 
@Component({ 
 
    selector: 'page-line', 
 
    templateUrl: 'line.html', 
 
}) 
 
export class LinePage { 
 

 
    commands: any[] = [] 
 

 
    constructor(public navCtrl: NavController, public navParams: NavParams, private http: Http) { 
 
    this.http.get('line.json').map(res => res.json()).subscribe((data) => { 
 
     this.commands = data.json(); 
 
     console.log(this.commands); 
 
    }) 
 
    } 
 

 
    ionViewDidLoad() { 
 
    console.log('ionViewDidLoad LinePage'); 
 
    } 
 

 
}

,這裏是JSON文件:

src/pages/subhome/line/line.json

{ 
 
\t "commands": [{ 
 
\t \t \t "title": "a", 
 
\t \t \t "desc": "b" 
 
\t \t }, 
 
\t \t { 
 
\t \t \t "title": "a", 
 
\t \t \t "desc": "b" 
 
\t \t }, 
 
\t \t { 
 
\t \t \t "title": "a", 
 
\t \t \t "desc": "b" 
 
\t \t }, 
 
\t \t { 
 
\t \t \t "title": "a", 
 
\t \t \t "desc": "b" 
 
\t \t } 
 
\t ] 
 
}

我試圖做的是 「記錄」 的JSON提前命令控制檯 謝謝!

回答

0

HTTP方法用於調用遠程服務器。 據我所知,這些方法不是用來調用你的應用程序 內的任何文件傳遞網頁中的數據,你可以使用這樣的事情this.navController.push(SecondPage, { param1: 'firstname', param2: 'lastname' });

參見教程here

如果你想JSON數據訪問,可以考慮將其存儲在一個變量,或者您可以使用本地存儲如下面

this.storage.set('myData', data); 

不要忘記導入和注入

import { Storage } from '@ionic/storage'; 
constructor (public storage: Storage){} 
0

您的JSON文件移動到文件夾的資產, 並通過

this.http.get('assets/line.json') 
叫它