Cannot find module on import with local JSON file - json

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

Related

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 ;

Showing data from a json file in Angular

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.

Angular 6 post prefixing http://localhost:4200/

I am trying to post a JSON file to a RESTful endpoint, but the request always prefixes "http://localhost:4200" to it.
Code:
app.component.ts
import {Component } from '#angular/core';
import {HttpClient} from '#angular/common/http';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: './app.component.css'
})
export class AppComponent {
private _url = 'website.com';
private _url2 = './assets/data/rfdata2.json';
public newGet = this.http.post(this._url, this._url2);
constructor(private http: HttpClient) {
this.newGet.subscribe(data => this.getArray = data);
}
}
./assets/data/rfdata2.json
[
{"frequency":2440.000, "name": "sig1", "id": "{mf0382mf4q8392-28nm3fq- q2u389mqf}"},
{"frequency":2460.000, "name": "sig2", "id": "{39n893-48398anjh9n8na-0398wnf}"},
{"frequency":2480.000, "name": "sig3", "id": "{fanb8903y84-may7md9a387kfa7m8}"}
]
Error text
ERROR Object { headers: Object, status: 404, statusText: "Not Found", url: "http://localhost:4200/website.com", ok: false, name: "HttpErrorResponse", message: "Http failure response for http://we…", error: "<!DOCTYPE html> <html lang="en"> <h…" }
(Obviously, website.com isn't the real endpoint. Just using it as a placeholder for my real website)
I also get the same error with a GET request. How do I get it to NOT prefix "http://localhost:4200/" to the POST URL?
Add a protocol to your URL.
private _url = 'https://website.com';

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

ng2-translate + Webpack for production

I'm trying to use the ng2-translate package with Webpack. In development mode it all works fine.
When i'm starting a build, it doesn't copy the language files to the "dist" directory.
Can anyone give me some advices how to change the output path, I tried to follow up https://github.com/ocombe/ng2-translate instructions but I doesnt provide any working example for webpack in production, and its not very clear how to use TranslateStaticLoader and change 18n/*.json.
If I add this I get an error with the libraries
#NgModule({
imports: [
BrowserModule,
HttpModule,
TranslateModule.forRoot({
provide: TranslateLoader,
useFactory: (http: Http) => new TranslateStaticLoader(http, '/assets/i18n', '.json'),
deps: [Http]
})
],
bootstrap: [AppComponent]
})
This is my app.module.ts
import {BrowserModule} from "#angular/platform-browser";
import { NgModule } from '#angular/core';
import {HttpModule} from '#angular/http';
import { AppComponent } from './app.component';
import {TranslateModule} from 'ng2-translate';
#NgModule({
imports: [
BrowserModule,
HttpModule,
TranslateModule.forRoot()
],
declarations: [
AppComponent
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
My app.component.ts
import { Component } from '#angular/core';
import {TranslateService} from 'ng2-translate';
import '../../public/css/styles.css';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
param: string = "world";
constructor(translate: TranslateService) {
// this language will be used as a fallback when a translation isn't found in the current language
translate.setDefaultLang('en');
// the lang to use, if the lang isn't available, it will use the current loader to get them
translate.use('en');
}
}
My app.component.html
<div>{{ 'HELLO' | translate:{value: param} }}</div>
and my json
{
"HELLO": "hello {{value}}"
}
Thanks for your help.
What errors do you have ? I'm using it in development mode and it's working perfectly.