Angular4: how do access local json? - javascript

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"
],

Related

How to insert Java-script file into a angular component.ts Type-script file and execute the onClick function for MEAN stack

import { Component } from '#angular/core';
import * as e from 'cors';
declare function click_fun():any;
#Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css']
})
export class RegisterComponent {
ngOnInit(): void{
}
click_fun(){
alert('Welcome')
}
}
"""How to call in JavaScript file that has all the code for database connection, storing data in MONGODB and credential authentication in click_fun()."""
- Let us assume our script file custom.js looks like this: -
var utilObj = {
dummyFunc: () => {
console.log('Calling dummy function!');
}
}
- Add your javascript/script file in scripts array in angular.json file.
"scripts": [
"src/custom.js"
],
Should look like this: -
- Add below code snippet in typings.d.ts. If this file doesn't exist, create one in src folder.
declare var utilObj:any;
Keep your variable name similar to property of script file. Here utilObj is the property name.
- Now, You can consume this script/js file directly in your component or .ts file.
You need not import the file in component file or .ts file now as we have given the typing defination for the script file already in typings.d.ts file.
Example: -
ngOnInit() {
console.log('Starting Application!');
utilObj.dummyFunc();
}
- Output: -

Reading data.json with HttpClient on Stackblitz?

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

Set up Angular 6 environment variables from .env

There's an angular 6 project using environment variables from ./project/src/environments/environment.prod.ts
export const environment = {
production: true,
testVar: 'gg',
};
The backend for this project also has env variables in a .env file, so a lot of variable duplicate angular env variables. It would be nice to have something like
export const environment = {
production: true,
testVar: process.env.TEST_VAR
};
, so I didn't have to duplicate variables.
ie
I'd like to parse variables from a .env file and assign their values to angular env variables during typescript compilation on the server.
How can this be done?
Maybe with webpack?
UPDATE
Some clarification. My .env file contains no json. It looks like this:
TEST_VAR=1
UPDATE
Since ng eject is not available for Angular 6, I don't seem to be able to hack into webpack config. Looks like deadend here.
ng eject
Overview
Temporarily disabled.
Ejects your app and output the
proper webpack configuration and scripts.
This question becomes also more and more important, when we want to containerize angular applications.
My research lead me to an idea, where I have to write a little node.js or typescript program, using dotenv for reading .env file and create the environment.ts file at buildtime, before starting ng serve.
You can create entries in the package.json like this:
...
"config": "ts-node set-env.ts",
"server": "npm run config && ng serve"
...
and run it with
npm run server
Here is a good explanation with an example typescript file:
https://medium.com/#ferie/how-to-pass-environment-variables-at-building-time-in-an-angular-application-using-env-files-4ae1a80383c
You can create a config file and populate in Run-time.
1) create a File(app-config.json) in assets folder with your variables
{ "servicesUrl": "https://localhost:8080/api"}
2) create a service (AppConfigService ) to read the file.
#Injectable()
export class AppConfigService {
private appConfig;
constructor (private injector: Injector) { }
loadAppConfig() {
let http = this.injector.get(HttpClient);
return http.get('/assets/app-config.json')
.toPromise()
.then(data => {
this.appConfig = data;
})
}
get config() {
return this.appConfig;
}
3) Next we need to tell our application to execute the loadAppConfig() method of our service.
import { NgModule, APP_INITIALIZER } from '#angular/core';
import { AppConfigService } from './services/app-config.service';
#NgModule({
...,
providers: [
AppConfigService,
{
provide: APP_INITIALIZER,
useFactory: appInitializerFn,
multi: true,
deps: [AppConfigService]
}
],
...
})
export class AppModule { }
4) create a function called "appInitializerFn" to call our service in AppModule (app.module.ts)
const appInitializerFn = (appConfig: AppConfigService) => {
return () => {
return appConfig.loadAppConfig();
}
};
...
#NgModule({
...
})
export class AppModule {}
5) import environment and use it :example
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { AppConfigService } from './services/app-config.service';
#Injectable()
export class DataContextService {
basePath: string;
constructor (private environment: AppConfigService, private http: HttpClient) {
this.basePath = environment.config.servicesBasePath;
}
getNames() {
return this.http.get(this.basePath + '/names/');
}
}
for more information please see:
link
If you want to use variables in build time you could use dotenv
As early as possible in your application, require and configure dotenv.
require('dotenv').config()
Create a .env file in the root directory of your project. Add environment-specific variables on new lines in the form of NAME=VALUE. For example:
DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3

How to include external JavaScript libraries in Angular 2?

I am trying to include an external JS library in my Angular 2 app and trying to make all the methods in that JS file as a service in Angular 2 app.
For eg: lets say my JS file contains.
var hello = {
helloworld : function(){
console.log('helloworld');
},
gmorning : function(){
console.log('good morning');
}
}
So I am trying to use this JS file and reuse all the methods in this object and add it to a service, so that my service has public methods, which in turn calls this JS methods. I am trying to reuse the code, without reimplementing all the methods in my typescript based Angular 2 app. I am dependent on an external library, which I cant modify.
Please help, thank you in advance.
With ES6, you could export your variable:
export var hello = {
(...)
};
and import it like this into another module:
import {hello} from './hello-module';
assuming that the first module is located into the hello-module.js file and in the same folder than the second one. It's not necessary to have them in the same folder (you can do something like that: import {hello} from '../folder/hello-module';). What is important is that the folder is correctly handled by SystemJS (for example with the configuration in the packages block).
When using external libs which are loaded into the browser externally (e.g. by the index.html) you just need to say your services/component that it is defined via "declare" and then just use it. For example I recently used socket.io in my angular2 component:
import { Component, Input, Observable, AfterContentInit } from angular2/angular2';
import { Http } from 'angular2/http';
//needed to use socket.io! io is globally known by the browser!
declare var io:any;
#Component({
selector: 'my-weather-cmp',
template: `...`
})
export class WeatherComp implements AfterContentInit{
//the socket.io connection
public weather:any;
//the temperature stream as Observable
public temperature:Observable<number>;
//#Input() isn't set yet
constructor(public http: Http) {
const BASE_URL = 'ws://'+location.hostname+':'+location.port;
this.weather = io(BASE_URL+'/weather');
//log any messages from the message event of socket.io
this.weather.on('message', (data:any) =>{
console.log(data);
});
}
//#Input() is set now!
ngAfterContentInit():void {
//add Observable
this.temperature = Observable.fromEvent(this.weather, this.city);
}
}

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

Categories

Resources