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
Related
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?
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)
I've read every other article or post about this I can find. I cannot for the life of me figure out where I'm going wrong with this simple task. (Specifically following this example.) I must be doing something obviously stupid but I've been looking at this so long I can't see it.
I have a json file called isRecognized.json in assets/mockData. I've added the mockData directory to my webpack config file so it's included in the /dist directory. If I go to http:localhost:4200/assets/mockData/isRecognized.json I'm able to see the file, so I know it's available.
However, when I try to retrieve the file using HTTP Client, it throws a 404 no matter what I try.
EDIT: I'm using Webpack, not Angular CLI.
app.component.ts
import { MyService } from './services/my.service';
import { Component, OnInit, Renderer2 } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
/*
* Main app component that houses all views.
*/
#Component({
selector: 'app-comp',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
constructor(
private route: ActivatedRoute, private service: MyService
) {}
ngOnInit() {
this.service.isRecognized();
}
}
my.service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
#Injectable()
export class MyService {
constructor(private http: HttpClient) { }
isRecognized() {
this.getJSON('isRecognized').subscribe(data => {
console.log(data);
});
}
getJSON(fileName): Observable<any> {
return this.http.get('http://localhost:4200/assets/mockData/' + fileName + '.json');
}
}
The error I get in the browser console is:
AppComponent_Host.ngfactory.js? [sm]:1 ERROR Error: [object Object]
at viewWrappedDebugError (core.js:9795)
at callWithDebugContext (core.js:15101)
at Object.debugCheckAndUpdateView [as checkAndUpdateView] (core.js:14628)
at ViewRef_.webpackJsonp../node_modules/#angular/core/esm5/core.js.ViewRef_.detectChanges (core.js:11605)
at core.js:5913
at Array.forEach (<anonymous>)
at ApplicationRef.webpackJsonp../node_modules/#angular/core/esm5/core.js.ApplicationRef.tick (core.js:5913)
at core.js:5746
at ZoneDelegate.webpackJsonp../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:391)
at Object.onInvoke (core.js:4756)
If I debug the error, I can see the body of the error is:
I have this working successfully in my app just using a URL like this:
private productUrl = 'api/products/products.json';
Notice that it does not have the localhost part of the path.
So try something more like this:
'assets/mockData/' + fileName + '.json'
Also ensure that your angular.json has the path listed under assets:
"assets": [
"src/favicon.ico",
"src/assets",
"src/api"
],
NOTE: I also didn't do anything to modify my webpack configuration. (But I'm using the CLI.)
If you want to look at some working code that accesses a json file, I have an example here:
https://stackblitz.com/edit/github-gettingstarted-deborahk
I would suggest subscribing in the component, and returning an Observable from the service:
Service:
#Injectable()
export class MyService {
constructor(private http: HttpClient) { }
isRecognized(fileName): Observable<any> {
return this.http.get('http://localhost:4200/assets/mockData/' + fileName + '.json');
}
}
Component:
export class AppComponent implements OnInit {
constructor(
private route: ActivatedRoute, private service: MyService
) {}
ngOnInit() {
this.service.isRecognized(fileName)
.subscribe(data => {
console.log(data);
});
}
}
While this might not be a direct solution to your specific problem, you should take a look at the npm package json-server. I use it to mock the API when developing and testing the client.
json-server npm
It will run a node web server on port 3000, and is really easy to use right out of the box.
See this tutorial example of how to use it:
Mock api with json-server
There might be better examples and setting up the proxy isn't necessary, but should be good enough.
Finally figured out the answer! I had this in my app.module.ts file as an import:
InMemoryWebApiModule.forRoot(InMemoryDataService, { dataEncapsulation: false })
Removing this fixed the issue immediately.
I am using routing in Angular to pull the url and store it in a global variable. It works well, except for when the url has an 'id' in it.
For example, my Url == '/site/1' however....
this.authService.current_route = this.router.url
// '/site' (not 'site/1' or 'site/:id')
How do I refactor to make this work?
My html looks like:
<span id="sitehead"> <a [routerLink]="['/site', site.id ]" (click)="changeroute()"> Site:</a></span>
My component:
import { Component, OnInit, Input } from '#angular/core';
import { DataService } from '../data.service';
import { Http } from '#angular/http';
import * as d3 from 'd3';
import { AuthService } from "../services/auth.service";
import { Router } from "#angular/router";
#Component({
selector: 'app-summary',
templateUrl: './summary.component.html',
styleUrls: ['./summary.component.css'],
})
export class SummaryComponent implements OnInit {
#Input() site;
constructor(private _dataService: DataService, private http: Http, public authService: AuthService, private router:Router ) {
}
changeroute(){
this.authService.current_route = this.router.url
console.log(this.authService.current_route)
}
Thanks!! Let me know if I can clarify
There's probably a less complicated way to get the current url, but in the past, I created a function that does it. Hopefully it suits your immediate needs.
constructor(route: ActivatedRoute) {
const path = this.getPath(route.snapshot);
}
private getPath(route: ActivatedRouteSnapshot): string {
const urlSegments = route.pathFromRoot.map(r => r.url);
return '/' + urlSegments.filter(segment => !!segment && segment.length).join('/');
}
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);
}
}