Ionic read local JSON file - json

I am trying to read a local JSON file in Ionic 3. I have saved the JSON file in assets folder as csvjson.json
I call the following function inside one of the services.
getProducts() {
console.log('Inside getProducts')
return this.http.get(this.apiHost)
.map((response: Response) => {
console.log(response);
return response.json();
});
}
and then store the result in
myArray = this.databaseprovider.getProducts();
console.log("Returned from getProducts:" + myArray.length);
However I get the output as
Returned from getProducts:undefined
Can you pls suggest where I am going wrong?

Put the <file-name>.json file in assets folder and change the request to following,
public getProducts() {
return new Promise((resolve, reject) => {
this._http.get("assets/<file-name>.json")
.map((response: Response) => {
console.log(response);
resolve(response.json());
});
});
}
Component file
this.databaseprovider.getProducts().then((result)=>{
myArray = result;
});
console.log("Returned from getProducts:" + myArray.length);

The easiest way is to use fetch() function like that:
readJsonData(){
fetch("../../assets/data/Parameters.json").then(res=>res.json()).then(json=>{
console.log("OUTPUT: ", json);
//DO YOUR STAFF
});
}```

When you call it in your Typescript File of your Page for example called yourPage.ts in the yourPage folder you can access the local JSON File by importing it:
yourPage.ts:
import * as JSONdata from "../../assets/csvjson.json" //You can name 'JSONdata' as you want
To call it:
getProducts() {
console.log(JSONdata);
}

import { HttpClient } from '#angular/common/http';
constructor(private http: HttpClient) { }
this.http.get("assets.data.json").subscribe((data:any)=>{
console.log(data);
});

Related

How to make the function wait until response comes back

I am trying to add this response data to a zip object and later calling the createZip() method to download file as a zip file. Problem is my file getting downloaded first and the response is coming back. If I try to run the function again then right file is getting downloaded because in the previous API call I already got the response data.
Can anyone help me with this. I am new to angular and don't know how to use async/await properly.
zipFile = new JSZip();
exportIcsReportInJSONFormat() {
this.icsService.getICSReport()
.subscribe(response => {
console.log("JSONFile",response)
this.jsonFile = response;
this.zipFile.file("ics-report_.json", response, {binary:true});
});
To create zip file and download.
createZip() {
this.zipFile.generateAsync({type:"blob"})
.then(function(content) {
saveAs(content, "example.zip");
});
}
You can use the async/await pattern with Promises, something like this:
zipFile = new JSZip();
async mapZip() {
try {
var response = await this.exportIcsReportInJSONFormat();
console.log("JSONFile", response)
this.jsonFile = response;
this.zipFile.file("ics-report_.json", response, { binary: true });
var content = await this.zipFile.generateAsync({ type: "blob" });
saveAs(content, "example.zip");
}
catch {
...
}
}
exportIcsReportInJSONFormat() {
this.icsService.getICSReport().toPromise();
}

How to check the existence of file before reading it in Angular?

I have a function that gets the data from a saved file into the myJson variable. How can I check that the file exists without it affecting the below methods? Also, the file is in another folder that the one of the src of the project. It is in the backend dedicated folder. How can I access it from Angular and also to check if the file exists?
import myJson from 'src/assets/myFile.json' ;
readFile() {
this.savedData=myJson;
console.log("this is data from file "+this.savedData);
return myJson;
}
constructor (){
this.savedData= this.readFile();
}
Giving more context to my comments, I would do the async function as follow:
public async readFile() {
return await new Promise((resolve,reject) => {
this.http.get("your_path_to_file").toPromise().then(res => {
resolve(res);
}).catch(err => {
reject(err);
});
});
}
Then the funcion that calls the readFile :
public getFile() {
this.saveData = this.readFile();
// more code here if needed
}
Then instead of calling it in the constructor I'd use the OnInit life cycle:
public ngOnInit(): void {
this.getFile();
}
More datails on why it's a bad practise to return a promise in the constructor here: Is it bad practice to have a constructor function return a Promise?

how to fetch data from json in angular 4

Hi everyone plz help me I have Json string which is I am getting from Node api .I want only single value from that string.
I have service.ts from which I am calling api and subscribe the data on my component file .
Json string is [{"_id":5,"name":"ram,shyam,kamal,kishore"}]
I want only name value. how to achieve this.
service.ts code is given below
empservicecall() {
return this.http.get("http://localhost:3000/api/Employee")
}
component.ts code is given below
GetEmpName(){
this.Emp.empservicecall()
.subscribe(
response =>{
this.name=response.json})
}
it is not working and also error is coming in this code at line response.json().
plz help me
The solution to your issue completely depends on which version of Angular you are on and whether you're using Http or HttpClient.
If you're using HttpClient, then:
empservicecall() {
return this.http.get("http://localhost:3000/api/Employee");
}
And in your Component:
GetEmpName(){
this.Emp.empservicecall()
.subscribe(response => {
console.log(response);
this.name = response[0].name
});
}
If you're using Http(which has been deprecated after the introduction of HttpClient in Angular 4.3 BTW), then:
import 'rxjs/add/operator/map';
empservicecall() {
return this.http.get("http://localhost:3000/api/Employee")
.map((res: any) => res.json());
}
And in your Component:
GetEmpName(){
this.Emp.empservicecall()
.subscribe(response => {
console.log(response);
this.name = response[0].name
});
}

How to parse xml to Json ionic 2

I have been on this problem for the past three days. I want to convert an XML which is retrieved via HTTP into JSON so I can display it in ionic 2. Here is my codes in a provider.. Any help will be much appreciated.. thank you!
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
import * as xml2js from "xml2js";
#Injectable()
export class News {
constructor(public http: Http) { }
public getData() {
this
.http
.get('https://www.ug.edu.gh/news.xml')
.map(res => {
var cleanedString = res.toString().replace("\ufeff", "");
xml2js
.parseString(cleanedString, (error, result) => {
console.log(result);
return result;
});
})
.subscribe((data) => {
console.log(data)
}, (err) => {
console.log(err)
});
}
}
For Parsing xml to json in ionic 2
You can install the typings for xml2json now using the command
typings install xml2json --save
If it generate error like this
'typings' is not recognized as an internal or external command,
operable program or batch file.
Then first use this command to install typing
npm install typings -g
Then run previous command
typings install xml2json --save
Then it'll work fine.
Hope it work for you
You're almost there. Things go wrong when you return the data from parseString method. You just should use a temporary variable, assign the result from the parseString method and return that temporary variable like so:
// ...
.map(res => {
let cleanedString = res.toString().replace("\ufeff", "");
let jsonData;
xml2js
.parseString(cleanedString, (error, result) => {
if(error) {
console.error(error);
jsonData = error;
} else {
jsonData = result;
}
});
return jsonData;
}).subscribe((data) => {
// ...
A more in depth description and an alternative method is given here.

Ionic2 and get Json

I am trying to use Ionic2 and I made a service to fetch a local stored 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);
});
}
I also a made PrintJson() method that just print the json for test purpose.I got the error:
GET http://localhost:8100/app/Ressources/slides.json 404 (Not Found)
I don't get why. And I can't find an easy and uptodate tutorial. Or should I use fetch()?
First copy your json to the following dir(you can create the folder "data"):
[appname]/www/data/data.json
Type in the following command in your console:
ionic g provider JsonData
It should create a provider for you.Go to that page and enter the following in load() function:
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);
});
});
}
I usually create an Observable wrapped around the api-call like this:
public GetItems() {
return Observable.create(observer => {
this._http.get('/app/Ressources/Items.json').map(res =>res.json()).subscribe(data=>{
observer.next(data)
observer.complete();
});
});
}
Then I have to subscribe on that method in order to get the results and do something with it. (You could be to delegate the result to a list in the GUI)
GetItems().subscribe(data=>{
myResult = data;
});
EDIT: It might help to put this in the class as well
export class MyClass{
static get parameters(){
return [[Http]];
}
}
Just try to get the response.json() rather than response.json().data in GetItems() method
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()
});
}