write to local file in angular service - json

I have tho following angular service:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
import { person } from '../interfaces/iperson';
import { item } from '../interfaces/iitem';
#Injectable({
providedIn: 'root'
})
export class PeopleserviceService {
constructor(private http: HttpClient) { }
getPersonData(): Observable<person[]> {
return this.http.get<person[]>('/assets/data/people.json');
}
completeTransaction(p: person, i: item){
return this.http.get<person[]>('/assets/data/people.json').toPromise().then(peopleData => {
if (!peopleData) {
return Promise.reject(new Error('No data received'));
}
for (const pers of peopleData) {
if (pers.id === p.id) {
pers.balance -= i.price;
break;
}
}
return this.http.put('/assets/data/people.json', JSON.stringify(peopleData)).toPromise();
});
}
}
but it gives the following error:
ERROR Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null},"status":404,"statusText":"Not Found","url":"http://127.0.0.1:4200/assets/data/people.json","ok":false,"name":"HttpErrorResponse","message":"Http failure response for http://127.0.0.1:4200/assets/data/people.json: 404 Not Found","error":"<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Cannot PUT /assets/data/people.json</pre>\n</body>\n</html>\n"}
Angular 17
core.mjs:9171:22
Angular 2
RxJS 6
Angular 14
How would I make this angular page running locally write to a file?
I have looked into the localforage package, but that doesn't seem to work.

assets/data/people.json lives on the server. When you are one Localhost, the client and the server are on the same computer, but usually the server is somewhere remote.
You cannot just write into a file on a server, if you want to do that you have to create a backend (i.e. NodeJS with Express) and create an endpoint that accepts some data, then on the Server you can write data on your file.
Keep in mind that this file is share with all the user, it's not a personal copy.

Related

How can I use the data obtained from a local json file in Angular?

I am using Angular and have stored a json file with data in it locally.
I am accessing the json file by importing it into my component through:
import * as data from '../../data/countries.json';
In my tsconfig.json file, I have set the following:
"resolveJsonModule": true
I am running into issues when using the data set.
The following works:
console.log(data[0].Country); and this returns me the name of the first country in the list, printing it to the chrome console.
However, when I attempt to use this data within the component.ts code, I get the following errors:
Code:
for (let i = 0; i < 50; i++) {
let name :string = data[i].Country;
this.addCoordinates(name, data[i].latitude, data[i].longitude);
}
Error:
core.js:6210 ERROR TypeError: Cannot read property 'Country' of undefined
at GlobeComponent.changeCountry (globe.component.ts:208)
at GlobeComponent.ngAfterViewInit (globe.component.ts:75)
at callHook (core.js:2573)
at callHooks (core.js:2542)
at executeInitAndCheckHooks (core.js:2493)
at refreshView (core.js:9537)
at refreshComponent (core.js:10637)
at refreshChildComponents (core.js:9263)
at refreshView (core.js:9516)
at renderComponentOrTemplate (core.js:9580)
Any help would be much appreciated! Thanks in advance.
I found a solution:
I've created a service that reads the JSON file through the HttpClient and returns the array of objects stores in your file.
This is the service:
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class LocalJSONService {
constructor(private http: HttpClient) { }
getLocalJSON$(): Observable<any>{
return this.http.get(`../assets/countries.json`);
}
}
And this is the globe.component.ts:
First inject the new service on the controller:
constructor(private localJSON: LocalJSONService) {
...
}
And then on the ngOnInit (you may place it on the ngAfterViewInit probably) I call a function called getLocalJSON$:
getLocalJSON$(): void {
this.localJSON
.getLocalJSON$()
.pipe(first())
.subscribe((countries: any[]) => {
countries.map((country: any) => console.log(country));
})
}
Instead of iterate over the countries you can store the values or call another function, whatever you need.

Angular observable subscribe JSON parsing issue

I have a service performing http.get on a Drupal API and retrieving JSON data.
The component utilising that JSON data keeps generating the following error:
ERROR in src/app/form-test/form-test.component.ts(18,28): error TS2551: Property 'included' does not exist on type 'Question[]'. Did you mean 'includes'?
From the following code:
constructor(private dataService: QuizService) { }
ngOnInit() {
this.dataService.fetch().subscribe(data => {
this.jsondata = data.included[0].attributes.field_json;
console.log(data, ': DATA');
});
}
I don't understand why there is a problem with the JSON and why it's trying to find includes instead of included in the JSON structure. Below is a screenshot of a sample of the JSON:
I have confirmed the structure of the JSON data (as confirmed from the image above), also from console logging the JSON data and that the API URL is live at the time Ay angular app is attempting to call it.
Can anyone advice what is the cause of this error and how can I resolve it?
UPDATE:
quiz.service.ts:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
export interface Question {
// title: string;
question: string;
included: any[];
}
#Injectable({
providedIn: 'root'
})
export class QuizService {
// tslint:disable-next-line: max-line-length
private quizURL: string = 'http://drupal-8-composer-drupal-test.com/jsonapi/node/quiz/31f020f7-34d9-4b9a-bd2b-0d567eb285dc/?include=field_questions&fields%5Bnode--quiz%5D=title,drupal_internal__nid,body&fields%5Bnode--question%5D=title,field_processed,body,field_options,field_json';
constructor(private httpClient: HttpClient) { }
fetch(): Observable<Question[]> {
return this.httpClient.get<Question[]>( this.quizURL );
}
}
The error states that data has type Question[]. It is an array, not an object. Typescript compiler tries to find an included variable in array and there's none. So it gives you an error.
Your JSON structure contains an array of questions in the included field. So the type which the fetch returns should be like { included: Question[] }:
fetch(): Observable<{ included: Question[] }> {
return this.httpClient.get<{ included: Question[] }>( this.quizURL );
}
Or you can process the response in service and return questions only:
fetch(): Observable<Question[]> {
return this.httpClient.get(this.quizURL)
.pipe(map((data: { included: Question[] }) => data.included));
}
.map operator gets the whole response object, extracts only questions and returns them as array.

Angular 7 - Cannot read JSON file from assets

Im trying to reading a JSON config file from my assets in angular project. I have created a Service and calling in App.Module.ts in a initializeApp function.
my jSON files are in src/assets/config/ folder
When it starts it shows me in console a Empty Json file "{}".
This is my service.
import { IConfig } from "../_model/config";
import { Injectable } from '#angular/core';
import { environment } from 'src/environments/environment';
import { HttpClient, HttpResponse } from '#angular/common/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
#Injectable()
export class Config {
static settings: IConfig;
constructor(private http: HttpClient) {
}
load() {
const jsonFile = `assets/config/config.${environment.name}.json`; // ${environment.name} could be 'prod' or 'dev'
return new Promise<void>((resolve, reject) => {
this.http.get(jsonFile).toPromise().then((response: IConfig) => {
Config.settings = <IConfig>response;
resolve();
}).catch((response: any) => {
reject(`Error en archivo de configuracion '${jsonFile}': ${JSON.stringify(response)}`);
});
});
}
and Config interface if you want check:
export interface IConfig {
config: {
production: boolean;
};
path: {
url_root: string;
};
timeZone: {
time: number;
};
}
console error
core.js:15724 ERROR Error en archivo de configuracion 'assets/config/config.dev.json': {}
it always goes for Catch and prints error message with anf EMPTY JSON, like if not exists.
If you need more info just tell me.
I think you have to add the "src/assets/config/" path to the assets: [] array your angular.json file. Then I think you have to recompile the server.
You need to step back twice. ../../
replace
const jsonFile = `assets/config/config.${environment.name}.json`;
with
const jsonFile = `../../assets/config/config.${environment.name}.json`;
Secure Recommention
However, I recommend that you have to place the config inside the environment files instead of the assets folder because the environment is secured by the browsers while assets will be public to anyone.

How to resolve api url issue in angular 6

I am trying to run this application in my local but not working.Many times i tried but i could not find the issue.I think api url issue.If i run this application i am getting below the error.How to resolve this issue? How can i run this application without error?
zone.js:2935 GET http://salembrothers.ca/app/api/getSettings/social 404 (Not Found)
products:1 Access to XMLHttpRequest at 'http://salembrothers.ca/app/api/getSettings/social' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
For full code : https://github.com/MarouaneSH/Angular-6-Shopping-cart-with-Laravel
api.service.ts:
import { HttpClient , HttpParams } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { catchError } from 'rxjs/operators/catchError';
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
import { Observable } from 'rxjs/Rx'
const apiUrl = "http://salembrothers.ca/app/api";
#Injectable()
export class ApiService {
constructor(private http:HttpClient) { }
get(path,params:HttpParams = new HttpParams()){
return this.http.get(`${apiUrl}/${path}`, {params})
.pipe(
catchError(this.handleError)
);
}
post(path,params){
return this.http.post(`${apiUrl}/${path}`, params)
.pipe(
catchError(this.handleError)
);
}
handleError(err:any){
return Observable.throw(err);
}
}
As the error message says 'has been blocked by CORS policy', you need to enable CORS in your API server, your API server/framework may also require to whitelist your 'http://localhost:4200' where you are running Angular.

Error occurred while trying to proxy request issue when configuring proxy for api call in angular6

I am new to angular 6 and trying to do api calls with the help of proxy from the following link.
angular 6 proxy configuration for api call
but I failed to get response from the server and it shows following error in terminal
[HPM] Error occurred while trying to proxy request /api/file2.php from localhost:4200 to http://localhost:1234 (ECONNREFUSED (https://nodejs.org/api/errors.html#errors_common_system_errors)
service.ts
import { Injectable } from '#angular/core';
import { HttpClient,HttpHeaders } from '#angular/common/http';
interface myData{
obj:Object;
}
#Injectable({
providedIn: 'root'
})
export class RecordsService {
constructor(private http:HttpClient) {
this.recordFunc();
}
recordFunc() {
let headers=new HttpHeaders();
return this.http.get<myData>('/api/file2.php');
}
}
proxyconfig.json
{
"/api":{
"target":"http://localhost:1234",
"secure":false,
"changeOrigin":true
}
}
I can't understand what the issue is here.I followed the instructions as per in the video.