Reading data.json with HttpClient on Stackblitz? - javascript

I have a tiny demo and it attempts to read app/data.json using the Angular HttpClient.
const post$:Observable<Post> = <Observable<Post>> http.get('./data.json');
However the HttpClient reponse says:
Failure during parsing ...
Thoughts?

Stackblitz currently doesn't serve static files except the case when they are in assets folder.
So you have two options here:
1) Import json directly as module
import data from './data.json';
console.log(data) // => {title: "Simulating HTTP Requsts", content: "This is off the hook!!"}
For more details See other answers
2) Move that json in assets folder(Note: you have to reload stackblitz to
make it working):
http.get('/assets/data.json')
Forked Stackblitz

Currently, you can't get the JSON directly over HTTP, but you can import it instead
data.json
it returns resource of index.html instead of the data you expected
online example
import { of } from 'rxjs';
import data from './data.json';
export class AppComponent {
constructor(http:HttpClient) {
}
ngOnInit(){
const post$ = of(data);
post$.subscribe(console.log);
}
}

i think there are some issues about reading local json in stackblitz it doesn't return plain json just the index.html instead. but another way is mocking a request from local json, you can try:
import data from './data.json'
ngOnInit(){
this.getDatas().subscribe(data=>{
console.log(data)
})
}
getDatas():Observable<any>{
return of(data).pipe(delay(1000));
}
forked DEMO

Related

Fetching data from local json file

I have a problem with the module not being found in React import. Here is my API from the file:
[
{
"poolNumber": "1",
"sender": "Damir",
"notRoutedReason": "NumberDoesntExist",
"sentDateTime": "2019-08-13T08:01:48.1535075Z",
"requestedDeliveryReportMaskText": "Submitted",
"deliveryReportReceivedDateTime": "2019-08-13T08:01:48.1535075Z",
"isUnicode": "FALSE",
"messageUUID": "4889e632-a314-45e2-89fd-35b07b4f9ff2"
},
{
"poolNumber": "1",
"sender": "Damir",
"notRoutedReason": "NumberDoesntExist",
"sentDateTime": "2019-08-13T08:01:46.3254032Z",
"requestedDeliveryReportMaskText": "Submitted",
"deliveryReportReceivedDateTime": "2019-08-13T08:01:46.3254032Z",
"isUnicode": "FALSE",
"messageUUID": "7f48626f-7dfe-4772-99e6-3a4c1df15e0e"
}
]
And then I'm trying to call it under imports so I can log(data)..
import React from 'react'
import dataJSON from './data.json'
const getData = async () => {
const response = await fetch(dataJSON)
const data = await response;
return getData
}
But I can't fetch data coz it isn't getting module I need.
How can I fix this?
If you're using Create React App this should work fine :
import dataJSON from './data.json'
console.log(dataJSON )
You could use axios / Promise based HTTP client for the browser and node.js to handle the request in the React componentDidMount life-cycle method.
https://github.com/axios/axios
But I agree that in CreatReactApp is easier to just:
import info from './data.json';
If you are using create-react-app, just import
import dataJson from './dataJson.json';
Please see my sandbox import json in react app
Tnx all for trying to help me, but my solution was putting .json file in public folder, and importing it in App.js... that Way engine didn't trow error and I resolved it with async/await.
For use import and export statements, you have to use es6, and for this, babal is required.
Maybe you have to add babel-plugin-import to your project: read if you have and how to install and configure here here)

Cannot load my JSON file: Http failure during parsing for JSON

I am attempting to load valid json but I am getting the error:
stackblitz
Http failure during parsing for ... .json
recipe.component.ts
url = '../../files/recipes.json';
recipes;
constructor(private fileService: FileLoaderService) {}
ngOnInit() {
this.fileService.getData(this.url).subscribe(res => console.log(res));
}
file-loader.service.ts
constructor(private http: HttpClient) { }
getData(url: string): Observable<any> {
return this.http.get(url);
}
What you have is not a valid JSON file. epascarello's answer tells you how to convert it to valid JSON, but another option is to just import the data directly.
Change the .json file extension to .ts
In your component, add import {recipes} from '../../files/recipes'
You've got your data! No need to mess around with http requests.
Having the export
export const recipes = [
{...}
]
makes it not a valid json document. Do not use export, remove it
JSON file should just be the json.
[
{...}
]
Couple this wrong and missing here:
This is not a valid JSON file (in the stackblitz). This is a constant which you can just import using a normal typescript import. If you want to load it using http, you should remove the export const recipes from the file
You should move the files folder to the assets folder of the project, this way the file can be loaded from the http server.
I spent a while ripping my hair out today (new to writing in StackBlitz). and even tried what was marked as answer on this thread, with no luck. Anyhow, the key seemed to be adding the .json file to the assets folder. Here's the link that finally got me immediate success. Hope that helps someone else keep their hair in tact. :-)
I've been asked to add code snippet, but not really too much to add, so I created a StackBlitz example that can be viewed, if desired. However, basically it all boils down to this: in StackBlitz when you're loading a local .json file, you do the same thing you normally would...except you ABSOLUTELY put that .json file in the "assets" folder (if you don't have one, create one)
this.http.get('/assets/user.json')
I added a StackBlitz example here

Angular4: how do access local json?

In Angular2 you could have a folder /data/ and a json file there and you could access it at localhost:4200/data/something.json.
This is no longer possible in Angular4.
Any ideea how to get it to work?
you can use this code
#Injectable()
export class AppServices{
constructor(private http: Http) {
var obj;
this.getJSON().subscribe(data => obj=data, error => console.log(error));
}
public getJSON(): Observable<any> {
return this.http.get("./file.json")
.map((res:any) => res.json())
.catch((error:any) => console.log(error));
}
}
here file.json is your local json file.
see here also
How to get a json file in angular2 using the Http class
also see the changlog of angular-cli for path
https://github.com/angular/angular-cli/blob/master/CHANGELOG.md#100-rc4-2017-03-20
Ofcourse its possible. Let's assume here is your json file
And here is your code to call the json
import { Injectable } from '#angular/core';
import { Http, Headers, Response } from '#angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map'
#Injectable()
export class YourService {
constructor(private http: Http) { }
getAdvantageData(){
let apiUrl = './assets/data/api/advantage.json';
return this.http.get(apiUrl)
.map( (response: Response) => {
const data = response.json();
return data;
});
}
}
You can use "require" too;
let test = require('./test.json');
I was facing the same issue, where my Observable Angular service was located at inside 'src/app/' folder and it was trying to load a local JSON file. I tried to put the JSON file inside the same app folder, inside a new 'api' folder, used various kinds of relatives/absolute routes, but it didn't help and I got 404 error. The moment I put it inside 'assets' folder, it worked. I guess there is more to it?
Maybe this link helps:
COMPONENT-RELATIVE PATHS IN ANGULAR
Based on this post, here is complete answer for Angular 6+:
From angular-cli doc, json can be considered as assets and accessed from standard import without use of ajax request.
Let's suppose you add your json files into "your-json-dir" directory:
add "your-json-dir" into angular.json file (:
"assets": [
"src/assets",
"src/your-json-dir"
]
allow import of json modules into typings.d.ts file to prevent from typescript errors:
declare module "*.json" {
const value: any;
export default value;
}
in your controller/service/anything else file, simply import the file by using this relative path:
import * as myJson from 'your-json-dir/your-json-file.json';
I figured it out.
In Angular2 I had the folder under the src folder.
In Angular4 you have to have it in the root folder.
Example:
Angular2:
root / src / data / file.json
Angular4:
root / data / file.json
You could add your folder location under Assets tag in angular.json
"assets": [
"src/favicon.ico",
"src/assets",
"src/api"
],

Angular2 dependency not injecting correct path

I am getting the following errors in my browser console, from trying to use localStorage with Angular2. It seems that the path it is generating isn't referring to the node_modules, but rather assuming that there is a localstorage.js in my site root (which there isn't). I am just referring to it normally (see my user.service below), so how do I get around this? All my other dependencies are working fine.
Error loading http://localhost:3000/localStorage.js as "localStorage" from http://localhost:3000/client/dev/user/services/user.service.js
import { Injectable } from 'angular2/core';
import { Headers } from 'angular2/http';
import { loalStorage } from 'localStorage';
#Injectable()
export class UserService {
private loggedIn = false;
constructor(private http: Http) {
this.loggedIn = !!localStorage.getItem('auth_token');
}
}
NB: I am fairly sure there isn't an actual problem with the localStorage installation, as if I run npm list localStorage, then it tells me I have localStorage#1.0.3 instaled.
If you want to use localStorage from an import, you need to configure it within SystemJS as described below:
System.config({
map: {
localStorage: 'node_modules/localStorage/lib/localStorage.js'
},
(...)
});
This way, you will be able to use the following import:
import loalStorage from 'localStorage';
See this question for more details since it's similar to the way to configure Lodash:
Lodash in angular2, declare var_:any not working

Typescript compiler error when importing json file

So the code is simple:
calls.json
{"SERVER":{
"requests":{
"one":"1"
}
} }
file.ts
import json = require('../static/calls.json');
console.log(json.SERVER);
the generated javascript is correct and when running the node js server, the console log json.SERVER prints '{ requests: { one: '1' } }', as it should.
The typescript compiler (commonjs) however, somehow does not particularly like this situation and throws: "Cannot find module '../static/calls.json'".
Ofcourse I tried writing a .d.ts file, like this:
declare module '../static/calls.json'{
var exp:any;
export = exp;
}
this then obviously throws: "Ambient module declaration cannot specify relative module name".
I also tried different variants, like:
declare module 'calls.json' {
import * as json from '/private/static/calls.json';
export = json;
}
and then requiring:
import json = require('calls.json');
None work properly and have their own little compiler errors :)
I want to use an external .json file because I use commonjs serverside and amd clientside and I want a single file for loading constants.
Use var instead of import.
var json = require('./calls.json');
You're loading a JSON file, not a module, so import shouldn't be used is this case. When var is used, require() is treated like a normal function again.
If you're using a Node.js definition, everything should just work, otherwise require will need to be defined.
TS 2.9 added support for well typed json imports. Just add:
{
"compilerOptions": {
"resolveJsonModule": true
}
}
in your tsconfig.json or jsconfig.json. Now imports such as:
import json = require('../static/calls.json');
and
import * as json from '../static/calls.json';
should be resolved and have proper typings too!
Another solution is to change data.json to data.ts and export like this
export default {
"key" : {
...
}
}
and import as you would expect:
import { default as data } from './data'
This can also be done by using import statement if using webpack v2 which is already packed with json-loader.
Note that this is not async
import data from './data.json';//Note that this is not async
Also, in your typings.d.ts file add the following wildcard module to avoid typescript error saying: Cannot find module
declare module "*.json" {
const value: any;
export default value;
}
For anyone interested in async imports, check this article by 2uality
As of Typescript 2.9 you can import JSON file natively without any additional hack/loader needed.
The following excerpt is copied from said link above.
...TypeScript is now able to import JSON files as input files when using the node strategy for moduleResolution. This means you can use json files as part of their project, and they’ll be well-typed!
./src/settings.json
{
"dry": false,
"debug":
./src/foo.ts
import settings from "./settings.json";
settings.debug === true; // Okay
settings.dry === 2; // Error! Can't compare a `boolean` and `number`
For Angular 6 it can work with simple HTTP get call as below
Service
//interface, could be Array , object
export interface ResultJSON{
}
//Read JSON file for 3DWide
getJSON() {
return this.http.get(this.filepathUrl);
}
Component :import both service and interface and use as below
resultJSON :ResultJSON;
this
.testService
.getJSON()
.subscribe((data: ResultJSON) => {
this.resultJSON= data;
console.log(this.resultJSON);
});

Categories

Resources