This is my doma.component.ts file:
import { Component, OnInit } from '#angular/core';
import {HttpClient} from '#angular/common/http';
#Component({
selector: 'app-doma',
templateUrl: './doma.component.html',
styleUrls: ['./doma.component.css']
})
export class DomaComponent implements OnInit {
constructor(private http:HttpClient) { }
auti=[];
dohvatiPodatke=function(){
this.http.get("http://localhost:9999/auti").subscribe(
(res:Response) => {
this.auti=res.json();
}
)
}
ngOnInit(): void {
this.dohvatiPodatke();
}
}
my doma.component.html:
<h1>Auti</h1>
<table>
<th>Marka</th>
<th>Model</th>
<th>Cijena</th>
<tr *ngFor="let auto of auti">
<td>{{auti.marka}}</td>
<td>{{auti.model}}</td>
<td>{{auti.cijena}}</td>
</tr>
</table>
and my json file:
{
"auti":[
{
"marka": "Mercedes",
"model": "AMG",
"cijena": "200000"
},
{
"marka": "Seat",
"model": "Leon",
"cijena": "150000"
}
]
}
I successfully compiled and ran the project but i only get the table structure with no data in it. Before that i started the json server on my 9999 port and i can access it via localhost/9999/auti. I really don' see what could be the problem here.
Maybe try this :
this.http.get("http://localhost:9999/auti").subscribe(res => this.auti = res)
You are trying to loop over the parent object instead of the child array. Replace this.auti=res.json(); with this.auti=res.json().auti;. So the HTTP callback would look like
this.http.get("http://localhost:9999/auti").subscribe(
(res:Response) => {
this.auti=res.json().auti;
}
)
Keep your json into assets folder
Use relative path to read it:
auti=[];
dohvatiPodatke=function(){
this.http.get("./assests/auti-jsonfile.json").subscribe(
(res:Response) => {
this.auti=res;
}
)
}
Related
I have a movies.json that contain a list of movies and I want to create a MoviesServices to get the data where I want.
My MoviesServices:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { HttpErrorResponse } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class MoviesService {
movies: string[];
constructor(private httpService: HttpClient) {
this.getMovies();
}
getMovies() {
this.httpService.get('../../assets/movies.json').subscribe(
data => {
this.movies = data as string[];
console.log(this.movies); // My objects array
},
(err: HttpErrorResponse) => {
console.log(err.message);
}
);
console.log(this.movies); // Undefined
}
}
Firstly, I have no idea why the first console.log() works and the second not, can you tell me why ?
Here is my component where I need to get the data:
import { Component, OnInit } from '#angular/core';
import { MoviesService } from '../services/movies/movies.service';
#Component({
selector: 'app-movies',
templateUrl: './movies.component.html',
styleUrls: ['./movies.component.css']
})
export class MoviesComponent implements OnInit {
title = 'films-synopsys';
movies;
constructor(private myService: MoviesService) {}
ngOnInit() {
console.log(this.myService.movies); // Undefined
}
}
Of course this is not working. Can you tell me how must I do ? I'm newbie angular
So basically you need to return an Observable from your service and then subscribe to it from your Component. You can then assign your response to the Component property movies
Try this:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable()
export class MoviesService {
constructor(private httpService: HttpClient) { }
getMovies() {
return this.httpService.get('../../assets/movies.json');
}
}
And in your Component:
import { Component } from '#angular/core';
import { MoviesService } from './movies.service';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
title = 'films-synopsys';
movies;
constructor(private myService: MoviesService) {}
ngOnInit() {
this.myService.getMovies()
.subscribe(res => this.movies = res);
}
}
Here's a Sample StackBlitz for your ref.
Change your method to return an Observable which you can subscribe to:
import { Observable } from 'rxjs/Observable';
...
getMovies(): Observable<string []> {
this.httpService.get('../../assets/movies.json').subscribe(
data => {
this.movies = data as string[];
return this.movies;
},
(err: HttpErrorResponse) => {
console.log(err.message);
}
);
}
In your calling code:
import { Subscription } from 'rxjs/Subscription';
this.myService.getMovies().subscribe(movies => {
console.log(movies); // My objects array
}
The reason the first console log works is because you are doing it within an observable's subscription. Subscriptions have three states, Next, Error, Complete and so when you console log the first time, within the subscription next state you get the value that was pushed out from the event stream.
In your component the reason why it doesn't work is due to the fact that observables are lazy, and that you need to initialize the data by calling this.myService.getMovies() first to make the subscription happen.
A better way to do this would been to pass observables around and use async pipe in the html template.
I'm trying to build an app with ionic that reads data from a local `.json' file and uses this data to fill a page. But I'm already struggling with importing the file into the page. What I currently have is:
import { Component } from "#angular/core";
interface Entry {
name: string,
telephone: string
}
interface EntryList {
entryList: Array<Entry>;
}
#Component({
selector: 'page-list',
templateUrl: 'list.html'
})
export class ListPage {
entryList: EntryList;
constructor() {
this.load_entries();
};
load_entries () {
this.entryList = JSON.parse(
// ?
)
};
}
The .json file contains entries like:
[
{"name": "Person A","telephone": "1234"},
{"name": "Person B","telephone": "12345"}
]
I don't know how to proceed from here on. What's the right way to get my data into the app?
Please try this:
constructor(public http: HttpClient) {
this.load_entries();
};
load_entries(filePath: string) { //filePath: 'assets/test.json'
this.http
.get(filePath)
.subscribe((data) => {
console.log(data);
});
}
Of course, you have to import HttpClient first.
import { HttpClient } from '#angular/common/http';
I have following JSON retrieved from Web service and I am able to get specific element in nested JSON by hard-coding the index in html. Below is the sample data. This is just a portion of entire JSON, I caught rest of them and they are all in same order.
Now, I would like to get "id" element in condition to Name. All names will be given, but index for Table where Names located are unknown. I need to be able to get "id" for all given names. How should proceed this?
{
"School": {
"Table": [
{
"Name": [ "Leo" ],
"id": [ "123" ],
"class": [ "A" ]
},
{
"Name": [ "Kelvin" ],
"id": [ "456" ],
"class": [ "B" ]
}
]
}
}
ngOnInit(): void {
this.appService.getData().subscribe(res =>
this.results = res,
error => console.log(error)
);
}
This might be what you're looking for:
School.Table
.filter(o => o.Name === 'condition')
.map(o => o.id)
For example:
<p *ngFor="let id of ids$ |async"> {{ id }} </p>
this.ids$ = this.service.getSchool()
.map((o: School) => o.Table
.filter(o => o.Name === 'condition')
.map(o => o.id))
it's already been said but use a data service. Once that has returned the JSON data it's much easier to transform it to exactly how you want it. I've done a bit to this recently. Here's an example of a data service that does exactly this. Once this.gearDataJSON = gearData; is populated you can easily process the data into something the easy to work with on the HTML side.
Component
import { Component, OnInit } from '#angular/core';
import { Subscription } from 'rxjs/Subscription';
import { Observable } from 'rxjs/Rx';
import { Injectable } from '#angular/core';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/map';
import 'rxjs/Rx';
import { GearDataService } from '../../services/geardata.service'
#Component({
selector: 'app-gears',
templateUrl: './gears.component.html',
styleUrls: ['./gears.component.css']
})
#Injectable()
export class GearsComponent implements OnInit {
constructor(public gearDataService : GearDataService) {}
gearDataJSON; // Holds a complete copy of gears.json data
manufacturerNames : string[]; // Bit of JSON that we want to chop off or process
ngOnInit()
{
this.gearDataService.getGearData().subscribe((gearData) => // Load in gear data and populate array for control and selection
{
this.gearDataJSON = gearData;
this.manufacturerNames = gearData.manufacturers;
});
}
DataService
import {Injectable} from '#angular/core';
import {Http} from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class GearDataService {
constructor(public http : Http) {}
getGearData()
{
return this.http.get("./assets/gears.json")
.map(res => res.json());
}
}
Suppose that your json was something like-
component.ts
school:any = {
Table:[
{
name: "Steve",
id:"123"
},
{
id:"456"
}
]
};
If you want the output html to look like you suggested you don't really need to match the name but can just use iteration.
component.html
<table>
<tr>
<ng-container *ngFor="let user of school.Table">
<td>{{user.name}}</td>
</ng-container>
</tr>
<tr>
<ng-container *ngFor="let user of school.Table">
<td>{{user.id}}</td>
</ng-container>
</tr>
</table>
Would that suffice?
I am developing the services of my application, but when I try to load the page it shows the following error:
Can't resolve all parameters for GameEditComponent: ([object Object],
[object Object], ?).
I tried in the service to put as an array or just leave any, but even then the error continued
game-edit.service.ts
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import { Observable } from 'rxjs';
#Injectable()
export class GameEditService {
constructor(private http: Http) { }
getGame(id): Observable<any> {
return this.http.get('http://localhost:8080/lightning/api/game' + id).map(res => res.json()).catch(error => {
throw new Error(error.message);
});
}
getManufactures(): Observable<any> {
return this.http.get('http://localhost:8080/lightning/api/manufacture').map(res => res.json()).catch(error => {
throw new Error(error.message);
});
}
getPlatforms(): Observable<any> {
return this.http.get('http://localhost:8080/lightning/api/platform').map(res => res.json()).catch(error => {
throw new Error(error.message);
});
}
}
game-edit.component.ts
import { ActivatedRoute, Params } from '#angular/router';
import { Component, OnInit } from '#angular/core';
import { GameEditService } from './game-edit.service';
#Component({
moduleId: module.id,
selector: 'app-game-edit',
templateUrl: './game-edit.component.html',
styleUrls: ['./game-edit.component.css', '../styles.css' ]
})
export class GameEditComponent implements OnInit {
constructor(private activatedRoute: ActivatedRoute, private gameEditService: GameEditService, private id) {
this.gameEditService.getPlatforms().subscribe(platforms => {
console.log(platforms);
}), erro => console.log(erro);
this.gameEditService.getManufactures().subscribe(manufactures => {
console.log(manufactures);
}), erro => console.log(erro);
}
ngOnInit() {
this.activatedRoute.params.subscribe((params: Params) => {
this.id = params['id'];
console.log(this.id);
});
this.gameEditService.getGame(this.id).subscribe(game => {
console.log(game);
}), erro => console.log(erro);
}
onSubmit(form){
console.log(form);
}
verificaValidTouched(campo){
return !campo.valid && campo.touched;
}
aplicaCssErro(campo){
return {
'subError': this.verificaValidTouched(campo)
}
}
}
This is the json that is coming, the first is for a selected game, the second is for the platforms and the third is for the manufacturers
json game selected
{
"id":1,
"name":"Street Fighter",
"category":"luta",
"price":20.5,
"quantity":1000,
"production":true,
"description":"descricao",
"image":"ps4.jpg",
"manufacture":
{
"id":1,
"name":"Sony",
"image":"ps4.jpg",
"imageFullPath":"http://localhost:8080/lightning/images/ps4.jpg"
}
}
json platforms
{
"id":1,
"name":"PC",
"image":"ps4.jpg",
"imageFullPath":"http://localhost:8080/lightning/images/ps4.jpg"
}
json manufactures
{
"id":1,
"name":"Sony",
"image":"ps4.jpg",
"imageFullPath":"http://localhost:8080/lightning/images/ps4.jpg"
}
Console
I'm using angular cli with with all packages in the most current versions.
I do not know if maybe this error is because of the platforms you have inside the game, or some other code problem, if you know something that could do to repair, I tried several solutions that I found through the internet, but none worked.
Thanks in advance.
The problem is the last argument in the component's constructor, private id. Angular will try to resolve this dependency, but can't find an injectable class for id. When looking at the code, I think there is no need to inject id into the constructor. Just define it as a property on your component:
// ... import statements
#Component({
moduleId: module.id,
selector: 'app-game-edit',
templateUrl: './game-edit.component.html',
styleUrls: ['./game-edit.component.css', '../styles.css' ]
})
export class GameEditComponent implements OnInit {
private id; // put the declaration of id here
// remove id declaration from the constructor, no need to inject it
constructor(private activatedRoute: ActivatedRoute,
private gameEditService: GameEditService) { // ...constructor code}
// other code
}
I solved it otherwise: My problem was that the HttpClient has a rare condition, it's not the same "import" line on the component that on the app.module...
On the Component is this:
import { HttpClient } from '#angular/common/http';
in app module is this:
import { HttpClientModule } from '#angular/common/http';
I'm currently learning Angular 2 and have confused myself with how to output data returned from a service to my template.
My API Response :
{
"site": {
"success": true,
"title": "foo",
"description": "bar"
}
}
My Service :
import { Injectable } from '#angular/core';
import {HTTP_PROVIDERS, Http, Response, Headers, RequestOptions } from "#angular/http";
import { Observable } from 'rxjs/Rx';
#Injectable()
export class ContentService {
constructor(private _http:Http) {}
getContent() {
return this._http.get('http://localhost:8080/api/foobar-endpoint/')
.map((res:Response) => res.json())
}
}
My Component :
import { Component, OnInit } from '#angular/core';
import { ContentService } from "../../services/content/content.service";
const template = require('./home.jade');
const styles = require('./home.sass');
#Component({
selector: 'home',
templateUrl: template,
styleUrls: [styles]
})
export class HomeComponent implements OnInit {
public foo = {}
constructor(private _contentService: ContentService) {}
ngOnInit() {
this.getContent();
}
getContent() {
this._contentService.getContent()
.subscribe(
data => {this.foo = data},
err => { console.log(err) },
() => console.log()
);
}
}
My Template :
pre
p {{ foo.site.title }}
If I place {{ foo | json }} in my template I can see the returned values in a JSON format, but when I try and output a single value, such as title I get undefined errors.
How can I access the values being returned?
I think the only thing you are missing here is the ?. Basically the problem is that when the components instantiates your foo property has no site param so angular throws the error.
So what you can do is either this:
{{foo.site?.title}}
Or this:
<p *ngIf="foo.site">{{foo.site.title}}</p>
This way angular won't try to bind the title before there is a site.