![](/img/trans.png)
[英]Use local json file with Cordova/ionic/Angular. Works in browser, but not on device?
[英]Angular 2 / ionic 2 read json file from local device file system
我正在開發一個有特殊要求的應用程序 - 該應用程序脫機工作並具有“同步”機制。 這意味着,按需,用戶可以將應用程序與服務器同步。 我實現了一個使用cordova的'FileTransfer'並且節點生成帶有最新數據的json文件的過程,並將其下載到本地文件系統。 現在,我天真地以為我可以使用stabndard htrp rquest來獲取數據到這個文件。 但它沒有用。 所以我檢查了我的設備的logcat,發現無法對'file://'協議執行http請求。 在編寫這些線條時,它實際上是有道理的。
那我怎么能這樣做呢? 如何在文件系統上獲取文件? 有沒有辦法偽造在設備或somwethibf上運行的服務?
謝謝!
問題是因為本地瀏覽器(計算機)和設備(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() }); }
只需使用“assets / data / Items.json”而不是“/assets/data/Items.json”作為文件路徑。 它將適用於瀏覽器和Android設備。
this.http.get('assets/path/to/file').success((res) => {
console.log(res);
});
您可能已經想到了這一點,但是:
在你的路徑中省略協議,所以不要使用'file://'
而是直接使用路徑到文件存儲的位置,例如在android上它可能是'/ assets / path / to / file'。 所以你得到:
this.http.get('/assets/path/to/file').success(function(response){ //do something });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.