[英]Angular 2 / ionic 2 read json file from local device file system
I am working on an app with a special requirement - the app works offline and has "sync" mechanism. 我正在开发一个有特殊要求的应用程序 - 该应用程序脱机工作并具有“同步”机制。 That means that on demand, the user can sync the app with the servers.
这意味着,按需,用户可以将应用程序与服务器同步。 I implemented a process that using cordova's 'FileTransfer' and node generates a json file with the most recent data, and downloads it to the local file system.
我实现了一个使用cordova的'FileTransfer'并且节点生成带有最新数据的json文件的过程,并将其下载到本地文件系统。 Now, I naively thought that I could just fetch the data using a stabndard htrp rquest to this file.
现在,我天真地以为我可以使用stabndard htrp rquest来获取数据到这个文件。 But It did not work.
但它没有用。 So I examined the logcat of my device and found that it is not possible to execute http requests to 'file://' protocol.
所以我检查了我的设备的logcat,发现无法对'file://'协议执行http请求。 While writing these lines it actualy makes sense.
在编写这些线条时,它实际上是有道理的。
Then how can I do that anyway? 那我怎么能这样做呢? How can I fetch a file on the file system?
如何在文件系统上获取文件? Is there a way to fake a service that runs on the device or somwethibf?
有没有办法伪造在设备或somwethibf上运行的服务?
Thanks! 谢谢!
The issue is because of different paths of json files in local browser(computer) and device (android). 问题是因为本地浏览器(计算机)和设备(android)中的json文件路径不同。 Create
data
folder inside the src\\assets
folder. 在
src\\assets
文件夹中创建data
文件夹。 Move your json file into that. 将您的json文件移动到该文件中。
When we run ionic serve
, it will move that folder (with file) into www\\assets
folder. 当我们运行
ionic serve
,它会将该文件夹(带文件)移动到www\\assets
文件夹中。 Then do following things: 然后做以下事情:
Import Platform
service of ionic2
ionic2
导入Platform
服务
import { Platform } from 'ionic-angular';
Inject Platform
Service. 注入
Platform
服务。
constructor(private http: Http, private platform: Platform ) { }
Use Platform
Service. 使用
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() }); }
Just use "assets/data/Items.json" instead of "/assets/data/Items.json" as file path. 只需使用“assets / data / Items.json”而不是“/assets/data/Items.json”作为文件路径。 It will work both on browser and android device.
它将适用于浏览器和Android设备。
this.http.get('assets/path/to/file').success((res) => {
console.log(res);
});
You may have figured this out, but: 您可能已经想到了这一点,但是:
Leave out the protocol in your path, so don't use 'file://' 在你的路径中省略协议,所以不要使用'file://'
Instead use the path directly to where the file is stored, for example on android it will probably be '/assets/path/to/file'. 而是直接使用路径到文件存储的位置,例如在android上它可能是'/ assets / path / to / file'。 so you get:
所以你得到:
this.http.get('/assets/path/to/file').success(function(response){ //do something });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.