Add new object to local json file in Angular 4 - json

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?

Related

Importing static local json file to Vue store (exclude from build)

I'm trying to have my add data from a local static JSON file to the Vue vuex store.
I want my JSON file separated from the bundle process, so that i can change the content anytime in future, without rebuilding the whole site.
I have my json file [test.json] in the public folder
And with the following code, i managed to import the data, but its still being bundled on build of the site.
import data from '../public/test';
export const state = () => ({
allData: {}
})
export const mutations = {
SET_ALL_DATA(state, data) {
state.allData = data
}
}
export const actions = {
nuxtServerInit({ commit }) {
commit('SET_ALL_DATA', data)
}
}
I have also tried hosting the JSON file on a web server and doing an axios call to it on nuxtServerInit like so. but the called upon json file still gets bundled, as changing the hosted json file does nothing to update the content.
export const actions = {
async nuxtServerInit ({ commit }, { $axios }) {
const res = await $axios.$get('https://www.amq.fariskassim.com/testjson/test.json')
commit('SET_ALL_DATA', res)
}
}
I'm all out of solutions so if anyone can point me in the right direction, i would be totally grateful

How to fix TypeError: req.url.toLowerCase is not a function

I'm setting up a service and i want to use a json file with mock data to start with. However i get a TypeError: req.url.toLowerCase is not a function when i use that service with the mock data, how can i resolve this error?
Service:
import mockCompetitions from '../../mocks/competitions-mock.json';
export class CompetitionsService {
constructor(protected http: HttpClient) { }
getCompetitions() {
console.log(mockCompetitions);
return this.http.get(mockCompetitions);
}
}
Component:
competitions: any = [];
constructor(private competitionsService: CompetitionsService) {}
ngOnInit(){
this.getCompetitions();
}
getCompetitions(){
this.competitionsService.getCompetitions().subscribe(data => {
this.competitions = data;
console.log(this.competitions);
}, err => console.error(err), () => console.log('Finished Loading...'));
}
I expect a list of names to be printed out on the page from the json file.
If you want to use httpclient to read local json file, put the json file in assets folder as name-of-the-file.json and make the http request by using assets folder as url. It is important that you put it in the assets folder, so that Angular can find it. So your code should look something like this:
export class CompetitionsService {
constructor(protected http: HttpClient) { }
getCompetitions() {
return this.http.get('./assets/name-of-the-file.json');
}
}
So no need to import the file.
For using json file as a data provider you can use import and require.
import data = require('your_file.json')
console.log("data : ", JSON.stringify(data));
You are using the JSON file as an url to your http.get().
If you want to test your service using mock data, I would recommend some HTTP mocking website, like mocky. Put your JSON file there and use the URL that the site generates for you in your http.get(). You won't have to change anything except that in your code.

ANGULAR 6 http get JSON

I am having trouble getting information from certain json file.
case 1 (works):
service:
private xmlToJson: string = 'https://rss2json.com/api.json?rss_url=';
getImg(Url: string) {
return this.http.get(this.xmlToJson + Url);
}
component:
private url='https://api.flickr.com/services/feeds/photos_public.gne';
public images: any = [];
this.imgDataService.getImg(this.url)
.subscribe(data => this.images = data);
HTML:
<h1>{{images.feed.title}}</h1>
case 2 (does not work):
service:
getImg(Url: string) {
return this.http.get(Url);
}
component:
private url = 'https://api.flickr.com/services/feeds/photos_public.gne?format=json&nojsoncallback=1';
public images: any = [];
this.imgDataService.getImg(this.url)
.subscribe(data => this.images = data);
HTML:
<h1>{{images.title}}</h1>
Any idea why case 2 doesn't work? I ran both JSONs here: https://jsonlint.com/ and they came out valid.
You have a CORS error.
Here is a StackBlitz showing the two calls and what is returned from the server. The call for the Flickr URL fails because the Flickr API doesn't (at least on this service) return headers for Access-Control-Allow-Origin to enable public access.
Ironically, you'll be able to call the web service from any code that is not running in a web browser.
Since you probably won't be able to convince them otherwise (others have tried), I would suggest you give up on Flickr.
A final note: You would be able to see the error if you opened your browser's developer tools and checked the console. That should be your first stop for any weird behaviour you encounter in web development.
Change the public images: any = []
to public images: any = {}
Images data isn't an array.
Instead of this.imgDataService.getImg(this.url) type this.imgDataService.getImg(this.url2)
you can try this approach if you know what kind of json response is expected then probably you can create class like
Example:
export class ImageModel{
name:string;
title:string;
src:string;
}
where name,title and src are json keys
then in you can do:
constructor(private httpService:HttpService){}
getImg(Url: string) {
return this.httpService.get<ImageModel>(
(image:ImageModel) => {return image}
}
new HttpService should automatically map your json data to the javascript class/Interface
and then you can read the image to get the json data.

ionic 2 http service get data local json file

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

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