Angular 2 NFor loop not displaying - json

I don't get any errors to go off and the JSON is returned from the backend fine.
Question is, have I done anything wrong in the code below?
JSON
{
"Data": [{
"ProfileId": "121212",
"Name": "Charles",
"info": {
"rating": "0",
"plot": "Nothing happens at all."
}
}]
}
Home.Component.ts
import { Component, OnInit } from "#angular/core";
import { HomeService } from './home.service';
import { Profile } from './profile';
import 'rxjs/add/operator/map';
#Component({
moduleId: module.id,
selector: "home-page",
templateUrl: "home.component.html",
styleUrls: ["home.component.css"],
providers: [ HomeService ]
})
export class HomeComponent implements OnInit {
constructor(private service: HomeService) {}
Profiles: Profile[];
getProfile(): void {
this.service
.getData()
.then(profiles => this.Profiles = profiles);
}
ngOnInit(){
this.getProfile();
}
}
Home.service.ts
import {Injectable } from "#angular/core";
import {Headers, Http, Response} from '#angular/http';
import 'rxjs/add/operator/toPromise';
import { Profile } from './profile';
#Injectable()
export class HomeService {
private usersUrl = 'http://localhost:8888/';
private headers = new Headers({'Content-Type': 'application/json'});
constructor(private http: Http) {}
getData(): Promise<Profile[]> {
return this.http.get(this.usersUrl)
.toPromise()
.then(response => response.json().data as Profile[])
.catch(this.handleError);
//let err = new Error('Cannot get object of this type');
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
}
home.component.html
<h2>HOME</h2>
<ul>
<li *ngFor="let prof of Profiles;">
{{prof.name}}
</li>
</ul>
Rendered as this in browser

{{prof.name}}
should be
{{prof.Name}}

Your picture gives a hint of the array being null with:
...ng-for-of: null
so besides the mention by Günther of that {{prof.name}} should be {{prof.Name}},
your JSON holds Data, (with capital letter), but in your get-request you are using data. This is actually case sensitive, so the following line
.then(response => response.json().data as Profile[])
should be:
.then(response => response.json().Data as Profile[])
that should populate your array correctly :)

Related

Angular 6: use a service to get local json data

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.

Can't read url as JSON data

I have this JSON data and I'm getting it's output to a html file using angular. I use a service to get JSON data and a component to create the template. After using the template, I'm getting only id value and name value, but not url value.
JSON:
{
"A":1,
"B":[
{
"id":1,
"name":"One",
"url":"http://myapp/rootpath/first"
},
{
"id":2,
"name":"two",
"url":"http://myapp/rootpath/second"
}
]
}
I'm taking the JSON data to postArray variable in the component and pass it to the html file.
search.service.ts:
import { Injectable } from '#angular/core';
import {Http,Response} from "#angular/http";
import { Observable } from "rxjs";
import "rxjs/Rx";
import {JsoncallItem} from "./jsoncall-item";
#Injectable({
providedIn: 'root'
})
export class ApiService {
private postsURL ="http://myapp/items";
constructor(private http: Http ) {}
getPosts(): Observable<JsoncallItem[]>{
return this.http
.get(this.postsURL)
.map((response: Response)=> {
return <JsoncallItem[]>response.json();
})
.catch(this.handleError);
}
private handleError(error: Response) {
return Observable.throw(error.statusText);
}
}
search.component.ts
import { Component, OnInit } from '#angular/core';
import { ApiService } from "./../search.service";
import { JsoncallItem } from "./../jsoncall-item";
import { error } from 'util';
import { SearchtermPipe } from './../searchterm.pipe';
#Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {
title = 'app';
_postsArray: JsoncallItem[];
constructor(private apiSerivce: ApiService){}
getPosts(): void {
this.apiSerivce.getPosts().
subscribe(
resultArray => this._postsArray = resultArray
)
//error => console.log("Error :: " + error ))
}
ngOnInit(): void{
this.getPosts();
}
}
search.component.html:
<div class="container">
<ul>
<li *ngFor="let post of _postsArray | searchterm: value">
{{post.id}}, {{post.name}}, {{post.url}}
<hr>
</li>
</ul>
</div>
Output shows the id and name of each data, but not showing the url. What could be the wrong here?

Can't print nested JSON data with Angular 6

I'm learning to code and just ran into this issue with Angular 6 which I can't seem to solve. I was able to get JSON's data before but now that it's nested I don't know how to get it's data. This is what I've done so far
Service
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/toPromise';
#Injectable()
export class TestService {
url = "http://localhost:80/assets/data/test.json";
constructor(private http:Http) { }
getTestWithObservable(): Observable<any> {
return this.http.get(this.url)
.map(this.extractData)
.catch(this.handleErrorObservable);
}
private extractData(res: Response) {
let body = res.json();
return body;
}
private handleErrorObservable (error: Response | any) {
console.error(error.message || error);
return Observable.throw(error.message || error);
}
}
Component
import { Component, OnInit } from '#angular/core';
import { Observable } from 'rxjs';
import { TestService } from './test.service';
#Component({
selector: 'ngx-test',
styleUrls: ['./test.component.scss'],
templateUrl: './test.component.html',
})
export class TestComponent implements OnInit {
observableTest: Observable<any>
errorMessage: String;
constructor(private testService: TestService) { }
ngOnInit(): void {
this.testService.getTestWithObservable().subscribe(
res => {
let user = res[0]["users"];
let user_data = user["data"];
console.log(user_data["name"]);
}
);
}
}
JSON
[{
"id": 1,
"users": {
"user_id": 14,
"data": [{
"name": "James",
"age": 20
},
{
"name": "Damien",
"age": 25
}]
}
}]
HTML
<div *ngFor="let x of user_data; let i = index">
{{x.name}}
</div>
I'd appreciate if someone can point me out the solution or what I'm doing wrong.
You need to save the data in an instance property to access it. user_data is local to your function, you cannot access it in the template so you should use something like this :
export class TestComponent implements OnInit {
observableTest: Observable<any>
errorMessage: String;
user_data: any;
constructor(private testService: TestService) { }
ngOnInit(): void {
this.testService.getTestWithObservable().subscribe(
res => {
let user = res[0]['users'];
let user_data = user['data'];
console.log(user_data['name']);
this.user_data = user_data; // here
}
);
}
}
There is some problems with your code:
export class TestComponent implements OnInit {
observableTest: Observable<any>
errorMessage: String;
user_data: any;
constructor(private testService: TestService) {
}
ngOnInit(): void {
this.testService.getTestWithObservable().subscribe(
res => {
let user = res[0]["users"];
this.user_data = user["data"];
console.log(user_data["name"]);
}
);
}
}
In Angular >= 4, pipe methods is better to handle Observable
this.http.get(this.url)
.pipe(
filter(...),
map(...)
)
With HttpClient (Http is deprecated), the .json() is done for you. You don't need your extractData function.
You have to initialize your variable. And use "this" to refer to it.

Angular 2/4 - Can't resolve all parameters for GameEditComponent: ([object Object], [object Object], ?)

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';

Async data handling in Angular

I'm trying to load a local JSON into my component, but I can't get the values from my service into my component. I can see the json data in the service but it is undefined in my component. Does anybody see what i'm doing wrong here ? Thanks.
Here is an SS of the console.log in both service and component
interfaces.json
{
"interfaces": {
"eth" : {"name" : "eth"},
"lte" : {"name" : "lte"},
"wlc" : {"name" : "wlc"},
"wlap" : {"name" : "wlap"}
}
}
interfaces.service.ts
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
#Injectable()
export class Interfaces {
constructor(public http: Http) {};
public getData() {
return this.http.get('/assets/interfaces.json')
.map((res) => {res.json(); console.log(res); });
};
}
interfaces.component.ts
import { Component, OnInit } from '#angular/core';
import { Interfaces } from './interfaces.service';
import { Observable } from 'rxjs/Rx';
#Component({
selector: 'interfaces',
providers: [
Interfaces
],
template: `
<ul *dropdownMenu class="dropdown-menu" role="menu">
<li *ngFor="let interface of interfaces | async" role="menuitem">
<a [routerLink]=" ['./interfaces/eth'] "routerLinkActive="active"
[routerLinkActiveOptions]= "{exact: true}" class="dropdown-item" href="#">
{{interface.name}}Main Ethernet
</a>
</li>
</ul>
`,
})
export class InterfacesComponent implements OnInit {
constructor(public interfaces: Interfaces) {}
public ngOnInit() {
this.interfaces.getData().subscribe((data) => { this.data = data; console.log(data); });
}
}
The reason that it's undefined is that you are not returning your response inside the map not that map is not working..
.map((res) => {console.log(res); return res.json(); }); // missing return here
or without brackets:
.map((res) => res.json());
I don't know what is wrong as I'm new to angular2, but this works for me.
interfaces.service.ts
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
#Injectable()
export class Interfaces {
constructor(public http: Http) {};
public getData() {
return this.http.get('/assets/interfaces.json');
}
}
interfaces.component.ts
import { Component, OnInit } from '#angular/core';
import { Interfaces } from './interfaces.service';
import { Observable } from 'rxjs/Rx';
export class InterfacesComponent implements OnInit {
constructor(public interfaces: Interfaces) {}
public ngOnInit() {
this.interfaces.getData().subscribe((data) => {
this.data = data;
console.log(data);
});
}
}