Cant fetch data from local json using Angular - json

I am trying to fetch data from a local json file so that i would manipulate the data in the view (if u choose UnitOne the only 'roles' u can pick are 'role1','role2','role3' etc.)
So i build a sample application just to demonstrate the whole deal.
Basically I'm getting this error message:
Error: Uncaught (in promise): SyntaxError: Unexpected token < in JSON
at position 0 SyntaxError: Unexpected token < in JSON at position 0 at
JSON.parse () at Response.Body.json
here's the code Link

Your http call is not getting the JSON file because it does not live at http://localhost/data.json. That call is returning some HTML, which is why you get the error you get.
You can import the JSON file using TypeScript instead of trying to request it via HTTP.
import { Component, OnInit } from '#angular/core';
import 'rxjs/add/operator/toPromise';
import { Http } from '#angular/http';
import { RootObject, Parameter, Infos, Info, ValidValues, Condition} from './data.model';
import json from './data.json'
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
data: RootObject;
print: string = '';
constructor(private http: Http) { }
ngOnInit() {
this.data = json as RootObject;
this.print = this.data.parameters[1].keyParameterName;
}
}
Here is a working version.
There may be prettier ways to write the code, but I'll leave that up to you. :)
If you absolutely must request the JSON via HTTP, then I recommend you place it in your assets directory and make a call to /assets/data.json instead. That might work. Either that or use a CDN/external URL to request it from. But keep in mind you would need to have CORS enabled on that server or your request will be blocked by your browser.

The only issue here is your json file is not within assets folder.
You should move that file to your assets folder , and then try with the same code , and it will work.
Keep your file in the root of assets , as you are trying to fetch
./data.json ,
if you move to some of folder name asdf within assets , then you
need to change it like ./asdf/data.json

Related

How to use 'require' to import a JSON in NestJS controller?

I'm trying to return a json file as a controller response, but I can't get the content of the json.
import { Controller, Get, Res, HttpStatus, Query } from '#nestjs/common';
import { Response } from 'express';
import * as MOCKED_RESPONSE_TS from './data/payment-method.data'; // this ts file is imported fine
const MOCKED_RESPONSE = require('./data/payment-method-mock'); // this json file is not found
#Controller('commons')
export class CommonController {
#Get('/payment-method')
getPaymentMoethod(#Res() res: Response): any {
res.status(HttpStatus.OK).send(MOCKED_RESPONSE);
}
}
Actually the log returns: Error: Cannot find module './data/payment-method' and the app doesn't compile
I have done this with express (even with typescript) and works fine.
I don't know if i have to setup my project to read jsons (I'm newby on nest). By the moment I have created a typescript file exporting a const with the json content and I called it successfuly
I guess the problem lies in the way you import your .json file (change import instead of const)
Another advice or solution would be to leverage the .json() method of the res object (which is actually the express adapter response object).
Let's try with this code:
Your common.controller.ts file:
import { Controller, Get, Res, HttpStatus, Query } from '#nestjs/common';
import { Response } from 'express';
import * as MOCKED_RESPONSE_TS from './data/payment-method.data'; // this ts file should still be imported fine
import * as MOCKED_RESPONSE from './data/payment-method-mock.json'; // or use const inside the controller function
#Controller('commons')
export class CommonController {
#Get('/payment-method')
getPaymentMoethod(#Res() res: Response): any {
res.status(HttpStatus.OK).json(MOCKED_RESPONSE); // <= this sends response data as json
}
}
Also in your tsconfig.json file, don't forget to add this line:
tsconfig.json
{
"compilerOptions": {
// ... other options
"resolveJsonModule": true, // here is the important line, this will help VSCode to autocomplete and suggest quick-fixes
// ... other options
}
Last thoughts: you could use the sendfile() method of the res object depending on whether you want to send back a json file or the content of your json file.
Let me know if it helps ;)
first make sure you are calling it correctly.
Are you getting any response at all? if not double check your method name since its spelled like this: getPaymentMoethod and it should be this: getPaymentMethod.
Secondly I would recommend requiring outside the method and setting it to a constant.
Lastly try wrapping it in JSON.stringify() to convert the response to a json stringified object

Angular 6 return JSON result intead of HTML template

Is it possible to return JSON result from Angular instead of the HTML template coz we want to build something similar to a API-server? Thanks.
Here is the example that return the HTML template, how can we just return JSON without using template?
What I want to return is just a simple json result instead of HTML.
{"ID" : "1", "Name" : "Apple"}
Here is the code.
import { Component, OnInit, Input } from '#angular/core';
#Component({
selector: 'app-noresultsfound',
templateUrl: './noresultsfound.component.html',
styleUrls: ['./noresultsfound.component.css']
})
export class NoresultsfoundComponent implements OnInit {
#Input() txtval: string;
constructor(private app: AppConstants) { }
noresultsfound = this.app.noresultsfound;
ngOnInit() {
}
}
Alex
I think, he meant that pure JSON should be returned to who ever requested it by endpoint request. At least i faced something like this.
For static json, i've found an answer: https://github.com/angular/angular-cli/issues/5029
bresleveloper commented on 6 Jul 2018
1. ng-build with your index.html set properly with its components. (or conditional app-components)
2. rename and copy the rendered to (for example) /src/search.html
3. in angular.json (angular-cli.json for pre v5) find "assets":
"assets": [
"src/favicon.ico",
"src/search.html",
"src/assets"
],
browse localhost:4200/search.html
enjoy :)
Interesting part comes when u try to generate that json somehow, with browser not being involved - like some automatic service sends a request to some angular endpoint, like: hosname/statistics and in response, it receives a json which depends on number of pictures and headers on this current hosname, like {siteName: 'test', pictures: 10, headers: 1}.

How to parse external JSON file in the .jsx file

I'm new with React and need some one with my json file Parsing problem. I am having a PerfCompare.jsx with a variable needed in the following compare. And i need this var parsing from a external JSON file(trscConfig.JSON). I am using this lines to do. but always get this SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
trscConfig.JSON
{
"server" : "http://myserver.com"
}
PerfCompare.jsx
import React, { Component } from 'react';
import { Form, Input, Button, Radio, Row, Table, Divider, Progress, Alert } from 'antd';
import math from 'mathjs';
import { stringify } from 'qs';
import PerffarmRunJSON from './lib/PerffarmRunJSON';
import JenkinsRunJSON from './lib/JenkinsRunJSON';
import benchmarkVariantsInfo from './lib/benchmarkVariantsInfo';
import './PerfCompare.css';
//import App_DATA from './trscConfig.JSON';
const server_2 = JSON.parse('./trscConfig.JSON').server;
Use fetch():
const response = await fetch('trscConfig.JSON');
const json = await response.json();
const server_2 = json.server;
Or, if your build tool doesn't support await yet:
fetch('trscConfig.JSON')
.then(response => response.json())
.then(json => {
const server_2 = json.server;
});
In either case, downloading the JSON file at runtime will mean the response will not be available immediately. If this is a React component, I suggest doing this in componentDidMount().
Alternatively, if the JSON file is a static asset:
import {server as server_2} from './trscConfig.JSON';
JSON.parse doesn't know how to make HTTP requests/read files - it just parses exactly what you've passed in. In this case, it's failing because it's trying to convert the literal string ./trscConfig.JSON into a JSON object!
There's two ways you could get this working:
Load in the JSON via your module bundler, as you're doing in the commented out line in your code. I believe Webpack (and most others) support this out of the box, but your configuration might have it disabled, intentionally or otherwise. It might also be because you're using uppercase file extensions - try it with a file that has .json in lowercase.
Use XMLHttpRequest, the Fetch API, or a third-party HTTP client library to download the JSON at runtime, and then parse the downloaded text.

Angular - JSON Put and Delete Returns 403 (But postman app works well)

I have an rest api which i could use post and get requests. But when i want to use put and delete request it returns error 403. But also when i try to put and delete with Postman app (an app for json requests) all is works well. Im really confused. Let me prove the problem with some screenshots.
(Im censored links for security, sorry for that)
Chrome console;
Postman App;
Any my put code;
/** PUT: update the firm on the server */
updateFirm (firm: Firm): Observable<any> {
console.log(firm);
return this.http.put(this.firmUrl+"put/"+String(firm.id), firm, httpOptions).pipe(
tap(_ => console.log(`updated firm id=${firm.id}`)),
catchError(this.handleError<any>('updateFirm'))
);
}
I will be very appreciated if you could help me. Have nice day
I had a similar situation and found out that Angular 2 performs a OPTIONS method before a POST is done! OPTIONS was missing in "Access-Control-Allow-Methods".
If I check your log, then I think that you should also allow OPTIONS:
With angular, and perl as a backend, I had to allow the following:
-"Access-Control-Allow-Methods" => 'GET,POST,PATCH,DELETE,PUT,OPTIONS',
Proxy solves your problem.
A nice and fast solution could be to borrow one (like https://cors-anywhere.herokuapp.com) to test then do your own.
Here is an example :
import { Component, OnInit } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
#Component({
selector: 'app-analyzer',
templateUrl: './analyzer.component.html',
styleUrls: ['./analyzer.component.scss']
})
export class AnalyzerComponent implements OnInit {
res;
constructor(private http: HttpClient) {
this.getDeck().subscribe(res => {console.log(res); this.res = res; });
}
ngOnInit() {
}
getDeck() {
const headers = new HttpHeaders({
'X-Requested-With': 'XMLHttpRequest'
});
return this.http.get('https://cors-anywhere.herokuapp.com/https://www.keyforgegame.com/api/decks/30763530-041c-4e15-b506-3456e79141d2/',
{headers: headers}
);
}
}
It looks like a CORS error, you are doing the http request from your local machine on localhost to the backend on a different URL. The only way to solve this would be to allow requests from different origins on the backend. Or possibly to run the backend on your local machine.
Your problem is about CORS for HTTP OPTIONS request.
Indeed, before the execution of the HTTP PUT request, your client has to make a OPTIONS request, in order to add your httpOptions variable, which contains your header.
So you have to authorize the execution of OPTIONS request in the code of your server.

Not able to access JSON data into angular(.ts) file

I am trying to implement internationalization for my web application by using ngx-translate . I am able to access JSON data in the HTMl file but not able to access JSON data in the angular(.ts) file. Can anyone suggest me how to access it in .ts file.
You get the input from json files like you call a backend service. The syntax is the same, but if you read from a local json file it is an synchronous call.
// Import HTTP Client
import { HttpClient } from '#angular/common/http';
// Define property
myDataObject: any;
// Dependency Injection
constructor(private http: HttpClient) {}
// Get the data
ngOnInit() {
this.myDataObject = this.http.get<any>("assets/json/data.json")
.map(response => response)
}
Now you can get the properties from you json object like:
this.myDataObject.myProperty