ionic 2 http service get data local json file - json

I have a ionic 2 small application that uses a local json file stored in the assets folder. This file provides bio data on historical people and so does not need to be edited in anyway. I can access the file in the home.ts like so
constructor(public navCtrl: NavController, public http: Http) {
this.http.get('../assets/people.json').subscribe(data => {
this.people = data.json();
});
Note this works and I can loop through the data via the *ngFor loop.
But I think this should go into a service. But I can't work out how to put this into a service and then access the data in my home pages. I searched around but can not find any solution.

I was able to do this thanks to this tutorial from TutorialsPoint. The tutorial demonstrates how to create a service, and I combined the instructions with ionic Storage to set and get data from a file stored locally.
export class SomeService {
...
getSomething(): Observable<Something[]> {
return this._http.get(this._someUrl)
.map((response: Response) => <Something[]> response.json())
.do(data => this.storage.set("some_key", data));
}
...
}

Service.js
return this.http
.request('assets/data/radio-stations.json')
.map(response => response.json());
contoller.js
this.service.getdata()
.subscribe(response => {
this.data = response.Radios;
}, err => {
console.log(err);
});

Related

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
});
}

Getting correct ID without sharing URL

I have an Angular 4 application where I am trying to fetch a single row (using ID) from a MySQL database. I am using NodeJS with ExpressJS. However, I am struggling finding a way to get the ID from the URL without sharing the exact URL-path, as that would lead to the website only rendering the JSON-object, and not the components.
server.js
app.get('api/books/:id', (req, res) => {
console.log(req.params.id);
});
If the URL is localhost:3000/books/3, the console will log :id. localhost:3000/api/books/3 will however log the correct ID to the console. The issue is that using the latter as my URL in my Angular routing will result in a shared path, which will not work.
Here's an example of how I use Angular's HttpModule to send a GET-request to the server:
this.http.get('api/books/:id')
.map(res => res.json())
.subscribe(data => {
this.bookDetail = data;
});
Here is my path from the routing using Angular's RouterModule:
{ path: 'books/:id', component: BookDetailComponent }
How would I go about solving this issue?
You need to create a function that on the init of that component, the angular app triggers the HTTP request to the server. for example, I have a blog application.
{ path: 'blogs/:id', component: BlogComponent },
ngOnInit() {
this.route.params.subscribe(params => this.blog = params.id);
this.getBlog(this.blog);}
getBlog(blog) {
this.blogService.getBlog(blog).subscribe(
data => { this.foundBlog = data;
if (data.comments) {
this.comments = data.comments;
}
getBlog(blog): Observable<any> {
return this.http.get(`http://localhost:3000/api/blogs/${blog}`).map(res => res.json());
}
the first is my route, the second is the init function on my blog component
the third is the get blog function on the blog component
the last is the get blog function on my blogservice, that send the HTTP request
hopefully that helps.

Add new object to local json file in Angular 4

I have a simple method to call the json file located in my assets folder
private jsonPath = '../assets/data/sample.json';
constructor(private http: Http) {
http.get(this.jsonPath)
.subscribe(response => {
this.posts = response.json();
})
Works well on reading it however I want to perform CRUD operation on it (for example create a new object). Is it possible to do?

Get past request without waiting for response (Angular 2 +)

I am looking for data in an API via Get request, I need the data inside my OnInit to use in composing other data. The problem is that the method is being called but it is as an async method (without await), it passes everywhere but when the return is obtained the excution of the main method has already been finished with no results. I tried the implementation of asynchronous methods but it did not solve.
service:
getObjects(): MyClass[] {
let objects = new Array<MyClass>();
this.obterTodos<MyClass>(this.uriApi)
.map(res => res.map(x => new MyClass(x.Description, x.Id)))
.subscribe(entities => {
objects = entities;
});
return objects ;
}
get request
public getObjects<TEntity>(url: string): Observable<TEntity[]> {
return this.httpService
.get(this.serviceUrl + url, this.options)
.map(res => res.json())
.catch(this.handleError);
}
component:
ngOnInit() {
this.myObjects= this.setorService.obterSetores();
console.log('this.myObjects is empty here');
}
so you'll want to subscribe to your observable in the component. This is typically done so the component can determine when the http request should be ran & so the component can wait for the http request to finish (and follow with some logic).
// subscribe to observable somewhere in your component (like ngOnInit)
this.setorService.obterSetores().subscribe(
res => {
this.myObjects = res;
},
err => {}
)
now the component knows when the http request finishes

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()
});
}