Showing data from a json file in Angular - json

This is my home.component.ts file:
import { Component, OnInit } from '#angular/core';
import {HttpClient, HttpResponse, HttpHeaders} from '#angular/common/http';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(private http: HttpClient) { }
cars=[];
fetchData=function(){
this.http.get("http://localhost:3000/cars").subscribe(
(res:Response)=>{
this.cars=res.json();
}
)
}
ngOnInit() {
this.fetchData();
}
}
home.component.html file:
<h1>Cars</h1>
<table>
<th>Id</th>
<th>Brand</th>
<th>Model</th>
<tr *ngFor="let car of cars">
<td>{{car.id}}</td>
<td>{{car.brand}}</td>
<td>{{car.model}}</td>
</tr>
</table>
and cars.json file:
{
"cars": [
{
"id": 1,
"brand": "Seat",
"model" : "Leon"
},
{
"id": 2,
"brand": "Mercedes",
"model" : "AMG"
}
]
}
I started the json server and compiled the project. The outcome is just the table structure without the fetched data. The json server is listening on the 3000 port and i'm using angular 7.0.3 version. Can somebody help me?

Try this:
const fs = require('fs');
let rawdata = fs.readFileSync('cars.json');
let cars = JSON.parse(rawdata);
or
const mycars = JSON.stringify(rawdata);
console.log(mycars);

cars=[];
fetchData=function(){
this.http.get("http://localhost:3000/cars").subscribe(
(res:Response)=>{
this.cars=res;
}
)
}
This fixed my problem. Thank you for the help.

Related

How show to link: localhost:4200/navigator?nameA - this is json data?

How show to link: localhost:4200/navigator?nameA - this is json data?
I have box.json, if click getBox() - need move on link localhost:4200/navigator?nameA and show namA, box, first.If will be nameB - to need move on link localhost:4200/navigator?nameB.
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '#angular/common/http';
#Injectable()
export class BoxService {
constructor(private http: HttpClient) {}
getBox(): Observable<Object> {
return this.http.get('/assets/data/box.json');
}
}
////
import { Component, OnInit } from '#angular/core';
import { HttpClient } from "#angular/common/http";
import { BoxService } from './box.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
box$:any;
constructor(private boxService: BoxService){}
getBox() {
this.box$ = this.boxService.getBox();
console.log(this.box$);
}
}
//
[
{
"nameA": "1A",
"title":"1 Hi",
"rum": [{"box":"box1", "first": "1first-box"}]
},
{
"nameA": "2A",
"title":"2 Hi",
"rum": [{"2box":"box2", "first": "2first-box"}]
},
{
"name": "B",
"title":"2 Hi"
}
]
<button (click)="getBox()">Get box</button>
<ul>
<li *ngFor="let a of box$ | async; index as i">{{ a.nameA }}
<div *ngFor="let y of a.rum ">
nameA: {{ y.box }}/{{y.first}}
</div>
</li>
</ul>

How can I access the json key value with help of typescript variable?

Json File
"Tamil": {
"Name": "பெயர்",
"Email": "மின்னஞ்சல்",
"Phoneno": "தொலைபேசி எண்",
"Password": "கடவுச்சொல்",
"CPassword": "கடவுச்சொல்லை உறுதிப்படுத்தவும்",
"Register": "பதிவு",
"Cancel": "ரத்துசெய்"
},
Ts File
import {Component, OnInit} from '#angular/core';
import * as data from '../home/lang.json';
#Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {
public language;
public value;
constructor() {
this.value = 'Tamil';
this.language = data[this.value].Name;
alert(this.language);
}
ngOnInit() {
}
}
Output
ERROR Error: "Uncaught (in promise): TypeError: _home_lang_json__WEBPACK_IMPORTED_MODULE_2___namespace[this.value] is undefined
HomePage#http://localhost:8100/home-home-module.js:128:9
HomePage_Factory#ng:///HomePage/ɵfac.js:5:10
But When I try this possibility is working fine:
this.language = data["Tamil"].Name;
But while trying this
this.language = data[this.value].Name;
It's Showing that error.
The only mistake you are doing is accessing Malayalam which does not exist in your JSON file, add Malayalam and it will work fine.
Some code fine tune I am doing which might help.
replace
import * as data from '../home/lang.json'
to coz TypeScript > 2.9 has a simplest way to do that
import data from '../home/lang.json
JSON File
{
"Tamil": {
"Name": "பெயர்",
"Email": "மின்னஞ்சல்",
"Phoneno": "தொலைபேசி எண்" ,
"Password": "கடவுச்சொல்",
"CPassword": "கடவுச்சொல்லை உறுதிப்படுத்தவும்",
"Register":"பதிவு",
"Cancel" : "ரத்துசெய்"
},
"Malayalam": {
"Name": "பெயர் m",
"Email": "மின்னஞ்சல் m",
"Phoneno": "தொலைபேசி எண் m" ,
"Password": "கடவுச்சொல் m",
"CPassword": "கடவுச்சொல்லை உறுதிப்படுத்தவும் m",
"Register":"பதிவு m",
"Cancel" : "ரத்துசெய் m"
}
}
Component
constructor() {
this.value = "Malayalam";
this.language = data[this.value].Name;
alert(this.language)
}
Hope this works.
The dynamic import returns Promise.
use case:
import * as data from '../home/lang.json'
#Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {
public language;
public value;
constructor() {
this.value = "Malayalam";
this.language = data.default <=== add `default`
[this.value]?.Name;
alert(this.language)
}
ngOnInit() {
}
}
You can print data in the console to see its structure.
You can make on http call to fetch the json data
constructor(
private httpClient: HttpClient
) { }
this.httpClient.get('../home/lang.json')
.subscribe((res) => {
this.data = res;
});
Or simply you can read the file as
this.data= require('../home/lang.json');
CheckThis
You can the value by
this.result =this.data[this.language].Name
Sample code
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
template:
`<input [(ngModel)]="language" (ngModelChange)="onSelection()" >
<h1>{{ result ? result : data[language].Name }}</h1>`,
})
export class AppComponent {
language = 'Tamil';
result='';
public data = {
"Tamil": {
"Name": "பெயர்",
"Email": "மின்னஞ்சல்",
"Phoneno": "தொலைபேசி எண்" ,
"Password": "கடவுச்சொல்",
"CPassword": "கடவுச்சொல்லை உறுதிப்படுத்தவும்",
"Register":"பதிவு",
"Cancel" : "ரத்துசெய்"
} ,
"Malayalam": {
"Name": "Name Malayalam",
"Email": "Email malayalam",
"Phoneno": "தொலைபேசி எண்" ,
"Password": "கடவுச்சொல்",
"CPassword": "கடவுச்சொல்லை உறுதிப்படுத்தவும்",
"Register":"பதிவு",
"Cancel" : "ரத்துசெய்"
}
}
onSelection() {
this.result =this.data[this.language].Name
}
}
I think you forgot to add Malayalam language in your json.
If it can be happen that language may not present in your json then you should do like this
this.language = data[this.value] ? data[this.value].Name : '';
Instead of blank you can use default language too. If defualt language available in your json file then you can use like this.
this.language = data[this.value] ? data[this.value].Name : data['defaultLanguage'].Name ;

Cannot find module on import with local JSON file

I have this simple angular project and I'm having trouble importing a local json file that I created. Here's the JSON file:
{
"id": 1,
"firstName": "Uziel",
"lastName": "Cabanban",
"car" : {
"brand": "Toyota",
"model": "Vios",
"year": 2017
}
}
The JSON file is stored in this directory: src/assets/sampleJson.json.
Here is my component that tries to import said json file:
import { Component, OnInit } from '#angular/core';
import SampleJson from '../assets/sampleJson.json';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
}
I haven't written anything yet as I'm getting a red line in the import SampleJson from '../assets/sampleJson.json
Any suggestion will be much appreciated
Thanks for all of the suggestions but I went another direction and didn't use import anymore. Instead I used require and I used it like this:
import { Component } from '#angular/core';
import { user } from './user.model';
declare var require: any;
var myUser: user = require('../assests/sampleJson.json');
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor () {
console.log(myUser);
}
}
So far it prints the contents of my json file
.json file is not a TypeScript module. Since you want local file (assuming it is hardcoded), you can do it by creating a .ts file and export a constant/variable from it like following:
sampleJson.ts
export const SampleJson = {
"id": 1,
"firstName": "Uziel",
"lastName": "Cabanban",
"car" : {
"brand": "Toyota",
"model": "Vios",
"year": 2017
}
}
Then in the component:
import SampleJson from '../assets/sampleJson'; // path can change
Hope this helps
More on TypeScript Modules: https://www.typescriptlang.org/docs/handbook/modules.html
Update
Or you can import a JSON file using
import * as SampleJSON from 'path/to/json/sampleJson.json
with TypeScript v2.9.+ according to this answer:
https://stackoverflow.com/a/50674344/1331040

Angular 4 - Mapping HTTP JSON Response

I am trying to setup a mean stack crud application. The routes and the functionality is setup and tested using postman. I am getting correct responses for all the routes. Now I am trying to add the view part where the routes are called internally by the Angular application. I am trying to setup a basic get route. Following is my component code:
import { Component, OnInit } from '#angular/core';
import { UserService } from '../user.service';
#Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
users: {};
constructor(private userService: UserService) { }
ngOnInit() {
this.getUsers();
}
getUsers() {
this.userService.getAllUsers().subscribe(data => this.users = data);
}
}
and the service contains the following code:
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class UserService {
constructor(private http: Http) { }
getAllUsers() {
this.http.get('/api/users')
.map(res => res.json());
}
}
A sample response of the route using postman is as follows:
{
"status": true,
"err": null,
"data": [
{
"_id": "59d5db344c46e83a14b94616",
"name": "test"
},
{
"_id": "59d5db3c4c46e83a14b94617",
"name": "hello"
}
]
}
It always telling me the following error:
Property 'subscribe' does not exist on type 'void'.
What am I doing wrong? Can someone point me the standard way to do this?
Try this :
You forgot to return in your getAllUsers()
getAllUsers() {
return this.http.get('/api/users')
.map(res => res.json());
}

Pull data from a json file and display it with a button

I am trying to pull data from a json file and display it, but I am unable to proceed with the program because I lack experience in coding Angular.
Currently using Angular 4.3, which uses HttpClientModule.
app.component.ts
import { Component, OnInit } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = '?';
data;
constructor(private http: HttpClient) {
}
ngOnInit(): void {
this.http.get('/src/app/students.json')
}
chgTab1() {
this.title = "Changed Title";
}
chgTab2() {
//Want to display the items from json file
}
}
students.json
[
{"id": "3", "mame": "Dama"},
{"id": "1", "mame": "ASD"},
{"id": "2", "mame": "Chris"},
{"id": "4", "mame": "Sass"},
]
import { Component, OnInit } from '#angular/core';
import { Http,Headers } from '#angular/http';
import 'rxjs/add/operator/map';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = '?';
data;
showData = false;
constructor(private http: Http) { }
ngOnInit(): void {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.get('/assets/students.json', { headers: headers }).map(res => res.json()).subscribe(data => {
this.data = data;
})
}
chgTab1(){
this.title ="Changed Title";
}
chgTab2(){
//Want to display the items from json file
this.showData = !this.showData;
}
}
I have edited the whole thing. It will now work for you. Ensure you have the path to your student.json in the correct place.I moved it to the assets directory