Reputation: 1025
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. Now, I naively thought that I could just fetch the data using a stabndard htrp rquest to this file. 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. 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?
Thanks!
Upvotes: 4
Views: 6272
Reputation: 356
Just use "assets/data/Items.json" instead of "/assets/data/Items.json" as file path. It will work both on browser and android device.
this.http.get('assets/path/to/file').success((res) => {
console.log(res);
});
Upvotes: 1
Reputation: 8736
The issue is because of different paths of json files in local browser(computer) and device (android). Create data
folder inside the src\assets
folder. Move your json file into that.
When we run ionic serve
, it will move that folder (with file) into www\assets
folder. Then do following things:
Import Platform
service of ionic2
import { Platform } from 'ionic-angular';
Inject Platform
Service.
constructor(private http: Http, private platform: Platform ) { }
Use Platform
Service.
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()
});
}
Upvotes: 4
Reputation: 450
You may have figured this out, but:
Leave out the protocol in your path, so don't use 'file://'
Instead use the path directly to where the file is stored, for example on android it will probably be '/assets/path/to/file'. so you get:
this.http.get('/assets/path/to/file').success(function(response){ //do something });
Upvotes: 0