Get data from a json file into Angular ts - json

Is there any way to get data from a JSON file to angular typescript file in order to use in web pages?
this.http.get<any>('http://localhost:81/CO226/project/loginResult.json').subscribe((res: Response)=>{
});
this is what I tried.

JSON file could be saved to assets directory inside your project and can be accessed through the following code
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class TempJsonService {
jsonUrl = 'assets/file.json';
constructor(private http: HttpClient) { }
getJson(): Observable<any> {
return this.http.get(this.jsonUrl);
}
}

Related

Error (HttpErrorResponse) getting data from json server using angular

I tried to make a practice task-app and basically I have to get all the task data from a json server. I'd like to display it in the browser console first but the data won't show up and it shows an error. I followed all the steps from the tutorial video I've watched but still I'm getting the error.
console error
This is my service
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable({
providedIn: 'root',
})
export class RestapiService {
constructor(private http: HttpClient) {}
getTasks() {
return this.http.get('http://localhost:3000/tasks');
}
}
My taskdisplay.component.ts
import { Component, OnInit } from '#angular/core';
import { RestapiService } from 'src/app/services/restapi.service';
#Component({
selector: 'app-taskdisplay',
templateUrl: './taskdisplay.component.html',
styleUrls: ['./taskdisplay.component.css'],
})
export class TaskdisplayComponent implements OnInit {
constructor(private service: RestapiService) {}
ngOnInit(): void {
this.getallTasks();
}
userTasks: any = [];
getallTasks() {
this.service.getTasks().subscribe((result) => {
this.userTasks = result;
console.log(this.userTasks);
});
}
}
Your setting of the server url should not be done in the request. In the error message you see the url getting parsed in a weird way.
Instead make the call as such http.get('tasks') and otherwise, follow the answer as described in this post:
How do I set the baseUrl for Angular HttpClient?

how can i fetch my local json file in angular 13.2 and display data with html

its literally my third day trying to do that.thats what i achieved ,it displays nothing
,what i really want to do is to fetch data from lacal json so that every json element will be displayed in a html block
Service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient) {
this.getJSON().subscribe(matches => console.log(matches))};
public getJSON(): Observable<any> {
return this.http.get("./matches.json");
}
}
component.ts
import { Component, OnInit } from '#angular/core';
import { ApiService } from '../api.service';
#Component({
selector: 'app-matches',
templateUrl: './matches.component.html',
styleUrls: ['./matches.component.css']
})
export class MatchesComponent implements OnInit {
constructor(private ApiService : ApiService) { }
ngOnInit(): void {
this.ApiService.getJSON().subscribe(data => {
console.log(data);
});
}
}
matches.json
[{"id":"1","homeTeam":"Es Tunis","awayTeam":"Tatawin","dateM":"2022-04-21","stade":"Rades","NBtickets":"20000"},
{"id":"2","homeTeam":"Rejiche","awayTeam":"Etoile du sahel","dateM":"2022-04-11","stade":"Mahdia","NBtickets":"15000"},
{"id":"3","homeTeam":"Cs Cheba","awayTeam":"Solimane","dateM":"2022-04-11","stade":"Cheba","NBtickets":"5000"},
{"id":"4","homeTeam":"Zarzis","awayTeam":"Club Africain","dateM":"2022-04-11","stade":"Jlidi","NBtickets":"10000"},
{"id":"5","homeTeam":"Olympique Beja","awayTeam":"Monastir","dateM":"2022-04-11","stade":"Boujemaa Kmiti","NBtickets":"15500"},
{"id":"6","homeTeam":"Ca Bizert","awayTeam":"Cs Sfaxien","dateM":"2022-04-11","stade":"Tayeb mhiri","NBtickets":"10000"},
{"id":"7","homeTeam":"Hammam-sousse","awayTeam":"Ben Gerdane","dateM":"2022-04-11","stade":"Bouaali hwar","NBtickets":"12000"},
{"id":"8","homeTeam":"hammam-Lif","awayTeam":"Metlaoui","dateM":"2022-04-11","stade":"Stade municipale","NBtickets":"10000"}]
why wont my code display anything?
ps:i tried many things such as importing file.json but nothing worked(im beginner)

Angular 'Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.'

I'm creating an Angular app which shows list of projects and list of users from postgresql database, but I'm having issues with showing list of users in html.
The problem is that Angular is considering my array as an object no matter what I do.
The same code worked for projects but didn't work for users.
This is my service:
import { environment } from "../../../environments/environment";
import { Observable } from 'rxjs';
import { Projet } from '../modele/projet.model';
import { Test } from '../modele/test.model';
import { HttpParams,HttpClient } from "#angular/common/http";
import { Injectable } from "#angular/core";
import { map } from 'rxjs/operators';
import { User } from '../modele/user.model';
import { Financement } from '../modele/financement.model';
#Injectable()
export class WebService {
constructor(private httpClient: HttpClient) { }
serverUrl: string = "http://localhost:8080/"
get(url: string): Observable<any> {
return this.httpClient.get(this.serverUrl + url);
}
}
The component :
import { Component, OnInit } from '#angular/core';
import { User } from '../../shared/modele/user.model';
import { Router } from '#angular/router';
import { WebService } from '../../shared/sevices/web.service';
import { FormGroup, FormBuilder, FormControl, Validators, Form } from '#angular/forms';
#Component({
selector: 'app-show-users',
templateUrl: './show-users.component.html',
styleUrls: ['./show-users.component.scss']
})
export class ShowUsersComponent implements OnInit {
ngOnInit(): void {
this.getData();
}
usersList: Array<User>
user: User
myForm: FormGroup;
constructor(private webService: WebService, private formBuilder: FormBuilder,private router: Router) { }
getData(): void {
this.webService.get("showUsers").subscribe(res => {
let response = JSON.parse(JSON.stringify(res))
this.usersList = response.data
})
}
}
The html :
<tr *ngFor="let user of usersList">
<td>{{user.name}}</td>
<td>{{user.username}}</td>
<td>{{user.email}}</td>
</tr>
This is the server response :
server response
NB: the EXACT same code worked for the object PROJECT
You need to make sure that the variable you pass into *ngFor is an array. You can make sure of this with Array.from(v) and can also strip any keys of an Object that might be sent from the serverside with Object.values(v):
this.webService.get("showUsers").subscribe(res => {
this.usersList = Array.from(Object.values(res.data.body.data));
})
In my case, I have a simple approach, but I spent a lot of time. You could try this:
datas: any;
this.token = JSON.parse(window.localStorage.getItem('token'));
this.authService.getData(this.token.id).subscribe(data => {
this.datas = data;
})
In the HTML template just use this.datas.id, this.datas.username instead of an *ngFor
You don't need this code:
let response = JSON.parse(JSON.stringify(res))
this.usersList = response.data
simply use:
this.userlist = res
Youe complete method:
this.webService.get("showUsers").subscribe(res => {
this.userlist = res
});

Console.log to html element - Angular 4

Simple question. I have the following response from web service and I am observing it on chrome console. How do I deploy this onto Html element in angular 4? I tried to convert into JSON, but I encountered with another problem so I just decided to go with what I received after parseString.
All I want to do is, to display those fields in html element using Angular. For now, I just have component.ts file and trying to do something in html but can't figure out.
import { HttpClient, HttpErrorResponse, HttpHeaders } from '#angular/common/http';
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
import { Observable } from 'rxjs/Observable';
import { RequestOptions, Response } from '#angular/http';
import { Injectable } from '#angular/core';
import { parseString } from 'xml2js'
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
//import { IMovie } from './movie';
#Injectable()
export class AppService {
private urlNorth = 'service';
constructor(private http: HttpClient) { }
getMovies(): Observable<any[]> {
const headers = new HttpHeaders();
headers.set('Content-Type', 'text/sml');
headers.set('Accept', 'text/xml');
headers.set('Content-Type', 'text/xml');
return this.http.get<any[]>(this.urlNorth, { headers })
.map(res => {
var result = res.text().replace('<string xmlns="service">', '').replace('</string>', '').replace(/</g, '<').replace(/>/g, '>');
parseString(result, (err, resultN) => {
if (err) {
return console.dir('invalid XML');
}
else {
console.log(resultN);
}
})
})
.catch(this.handleError);
}
private handleError(err: HttpErrorResponse): ErrorObservable {
// in a real world app, we may send the server to some remote logging infrastructure
// instead of just logging it to the console
const errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
console.error(errorMessage);
return Observable.throw(errorMessage);
}
}
Log data
This code:
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
Does not belong in your service file. This is a component decorator and it should be on your component. Like this:
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private _appService: AppService) { }
getProduction() {
this._appService.getProduction()
}
}
Then your index.html file should use the tag to display the HTML.
In looking at your code more closely, there are other issues as well. For example, you are calling getProduction two times. You should not be calling it from the service constructor.
Also, the subscribe should be in the component, not the service.
And you should be using Http OR HttpClient, not both.
And TestBed is only for use in tests ... not in services.
I have a more complete example of a working component/service here: https://github.com/DeborahK/Angular-GettingStarted in the APM-Final folder. Consider looking through that code (or starting with that code) and making adjustments as needed for your application.
Here is a working service. (Without a plunker I can't successfully show this with your code. So you will need to make the appropriate replacements for your example.)
Service
import { Injectable } from '#angular/core';
import { HttpClient, HttpErrorResponse } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import { IMovie } from './movie';
#Injectable()
export class MovieService {
private moviesUrl = './api/movies/movies.json';
constructor(private http: HttpClient) { }
getMovies(): Observable<IMovie[]> {
return this.http.get<IMovie[]>(this.moviesUrl)
.do(data => console.log(JSON.stringify(data)))
.catch(this.handleError);
}
private handleError(err: HttpErrorResponse): ErrorObservable {
// in a real world app, we may send the server to some remote logging infrastructure
// instead of just logging it to the console
const errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
console.error(errorMessage);
return Observable.throw(errorMessage);
}
}
Component:
import { Component, OnInit } from '#angular/core';
import { IMovie } from './movie';
import { MovieService } from './movie.service';
#Component({
templateUrl: './movie-list.component.html',
styleUrls: ['./movie-list.component.css']
})
export class MovieListComponent implements OnInit {
movies: IMovie[];
errorMessage: string;
constructor(private movieService: MovieService) { }
ngOnInit(): void { this.getMovies(); }
getMovies(): void {
this.movieService.getMovies()
.subscribe(
(movies: IMovie[]) => this.movies = movies,
(error: any) => this.errorMessage = <any>error);
}
}

GET http://localhost:4200/src/app/ficheros/nacionalidades.json 404 (Not Found)

I'm desperate.
My problem is that I write the full path to my json file (I tried different possibilities) but it returns me an error 404 (GET http://localhost:4200/src/app/ficheros/nacionalidades.json 404 (Not Found)). I was investigating before asking the question. I dont know what I'm doing wrong and I'm not an expert. I leave my code so that you see it.
The component:
import { Component, OnInit } from '#angular/core';
import { Servicio1Service } from './../../services/servicio1.service';
#Component({
selector: 'app-componente-hijo1',
templateUrl: './componente-hijo1.component.html',
styleUrls: ['./componente-hijo1.component.css']
})
export class ComponenteHijo1Component implements OnInit {
listaPersonas: any;
constructor( private _servicio1service: Servicio1Service ) { }
ngOnInit() {
this._servicio1service.getTodasPersonas().subscribe((personas) => {
this.listaPersonas = personas;
console.log("this.listaPersonas");
console.log(this.listaPersonas);
});
}
}
The service:
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class Servicio1Service {
constructor( private _http:Http ) { }
getTodasPersonas(){
return this._http.get("./src/app/ficheros/nacionalidades.json").map((res) => res.json());
}
}
Structure of project:
src-app-{components,ficheros,services}
Thank you in advance.
I once tried to load a local json like you but it didn't work.
The solution was to put the json file in assets folder.
Then in your code :
getTodasPersonas(){
return this._http.get("assets/nacionalidades.json").map((res) => res.json());
}
Hope it can solve your problem :)
Best regards