How to display JSON objects in Angular2 views - javascript

New to Angular and I have the JSON available to me in the console. So the backend/REST call is functioning correctly. However I'm struggling to understand how to show the JSON in the view for the component.
Console screenshot:
app.component.ts
import { Component } from 'angular2/core';
import { TradeshowComponent } from './tradeshow/tradeshow.component';
#Component({
selector: 'app-container'
})
export class AppComponent {
constructor() { }
}
tradeshow.component.ts
import { Component, View } from 'angular2/core';
import { CORE_DIRECTIVES, NgIf, NgFor } from 'angular2/common';
import { DataService } from '../shared/services/data.service';
import { DashboardLayoutComponent } from '../dashboard_layout/dashboard_layout.component';
import { HTTP_PROVIDERS } from 'angular2/http';
#Component({
selector: 'tradeshow',
providers: [DataService, HTTP_PROVIDERS]
})
#View({
templateUrl: 'src/app/tradeshow/tradeshow.component.html',
directives: [DashboardLayoutComponent, NgIf, NgFor]
})
export class TradeshowComponent {
constructor(private _dataService: DataService) { this.getTradeShows() }
getTradeShows() {
this._dataService.getTradeShows()
.subscribe(
tradeshows => this.tradeShows = tradeshows
error => console.error('Error: ' + err)
);
}
}
And the HTML I'm using is:
tradeshow.component.html
<div *ngFor="#tradeshows of tradeshows">{{ tradeshows.name }}</div>
And my service looks like this:
data.service.ts
import { Injectable } from 'angular2/core';
import { Http, Response } from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import {Config} from '../../config/config';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
#Injectable()
export class DataService {
// API path
baseUrl: string = '/api';
authUrl: string;
apiUrl: string;
registerUrl: string;
constructor(private _http: Http, private _config: Config) {
this.apiUrl = this._config.get('apiUrl') + this.baseUrl;
this.authUrl = this._config.get('apiUrl') + '/auth';
this.registerUrl = this._config.get('apiUrl') + '/register';
}
getTradeShows() {
return this._http.get(this.getApiUrl('/tradeshow/list'))
.map((res: Response) => res.json())
.catch(this.handleError);
}
}

This looks like a bug
getTradeShows() {
this._dataService.getTradeShows()
.subscribe(
tradeshows => this.getTradeShows() = tradeshows,
error => console.error('Error: ' + err)
);
}
it should be
getTradeShows() {
this._dataService.getTradeShows()
.subscribe(
tradeshows => this.tradeshows = tradeshows
error => console.error('Error: ' + err)
);
}
You can remove NgIf, NgFor from
directives: [DashboardLayoutComponent, NgIf, NgFor]
these are now globally available.
Change
<div *ngFor="#tradeshows of tradeshows">{{ tradeshows.name }}</div>
to
<div *ngFor="#tradeshow of tradeshows">{{ tradeshow.name }}</div>
#Child() was removed a while ago
})
#View({
should be replaced by ,
I made an error in this line
tradeshows => this.tradeShows = tradeshows
should be (lowercase S)
tradeshows => this.tradeshows = tradeshows
Plunker example

Related

Angular 9 application "NgFor only supports binding to Iterables such as Arrays" error

I am working on a Contacts app with Angular 9. I get a list of contacts via the following service:
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Contact } from '../models/Contact';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
#Injectable({
providedIn: 'root'
})
export class ContactsListService {
contactsUrl = 'https://randomuser.me/api/?&results=500&inc=name,location,email,cell,picture';
constructor(private http:HttpClient) { }
getContcts():Observable<Contact[]> {
return this.http.get<Contact[]>(`${this.contactsUrl}`);
}
}
The Contacts List component is as follows:
import { Component, OnInit } from '#angular/core';
import { from } from 'rxjs';
import { ContactsListService } from '../../services/contacts-list.service';
import { Contact } from '../../models/Contact';
#Component({
selector: 'app-list',
templateUrl: './list.component.html',
})
export class ListComponent implements OnInit {
contactsList:Contact[];
constructor(private ContactsListService:ContactsListService) { }
ngOnInit(): void {
this.ContactsListService.getContcts().subscribe(contactsList => {
this.contactsList = contactsList;
});
}
}
Trying to iterate the contacts list this way
<ul *ngFor="let contact of contactsList">
<li>{{contact.name.first}}</li>
</ul>
throws the error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
That very likely means contactsList is not an array.
What am I doing wrong?
The URL is returning an object of the form
{
results: [],
info: {}
}
Use RxJS map to map the results obtained from the API.
Service
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { pipe } from 'rxjs';
import { map } from 'rxjs/operators';
import { Contact } from '../models/Contact';
export class ContactsListService {
contactsUrl = 'https://randomuser.me/api/?&results=500&inc=name,location,email,cell,picture';
constructor(private http:HttpClient) { }
getContcts():Observable<Contact[]> {
return this.http.get<Contact[]>(`${this.contactsUrl}`)
.pipe(map(response => response['results']));
}
}
Assign empty array to contactsList on declaration.
Component
import { Component, OnInit } from '#angular/core';
import { from } from 'rxjs';
import { ContactsListService } from '../../services/contacts-list.service';
import { Contact } from '../../models/Contact';
#Component({
selector: 'app-list',
templateUrl: './list.component.html',
})
export class ListComponent implements OnInit {
contactsList: Contact[] = []; // assign empty array
constructor(private ContactsListService:ContactsListService) { }
ngOnInit(): void {
this.ContactsListService.getContcts().subscribe(
contactsList => { this.contactsList = contactsList; },
error => { // always good practice to handle error when subscribing to HTTP observables }
);
}
}
Seems like the endpoint 'https://randomuser.me/api/?&results=500&inc=name,location,email,cell,picture' does not return an array. To check it you may open it in the browser, or check in the network tab of the chrome developers tools while your app running

Property 'push' does not exist on type 'any[]'

When i'm compile the angular code the compiler show me "Property 'push' does not exist on type 'any[]' " this error. Bellow the .service.ts and .component.ts code respectively.
Service.ts file
import { Injectable } from '#angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from '#angular/fire/firestore';
import { AngularFireDatabase} from 'angularfire2/database';
#Injectable({
providedIn: 'root'
})
export class UserService {
readonly userspath = "Development/users/users";
collectionRef= "Development"
ref = "Development"
usersRef="users"
public usersArray = [];
constructor(public af: AngularFireDatabase) { }
getUser(){
return this.af.database.ref(this.ref).child(this.usersRef)
}
}
component.ts file
import { Component, OnInit } from '#angular/core';
import { UserService } from '../services/user.service';
import { Router } from '#angular/router';
import { User } from '../models/user';
import { Observable } from 'rxjs';
#Component({
selector: 'app-employee',
templateUrl: './employee.component.html',
styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {
public user = [];
usersArray = [];
constructor(
private userservice:UserService,
private router: Router
) { }
title = "Employees";
ngOnInit( ) {
this.userservice.getUser().on('value',snapshot => {
snapshot.forEach(data => {
this.usersArray.push(data.val());
})
})
}
VScode show me Property 'push' does not exist on type 'any[]' this error
Try This,
ngOnInit( ) {
this.userservice.getUser().on('value',snapshot => {
this.usersArray = [];
snapshot.forEach((data:any) => {
this.usersArray.push(data.val());
})
})

GET http://localhost:4200/api/x.json 404 (Not Found) - angular 2

Hello, There is a problem with a project that does not recognize a json file - and I do not know why. Is there anything I need to change or make it work?
this is my folders:
this is my service:
import { Injectable } from "#angular/core";
import { Ibrides } from "./brides";
import { HttpClient, HttpErrorResponse } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
#Injectable()
export class brideService {
private _brideUrl = 'api/brides.json';
constructor(private _http: HttpClient) { };
getBrides(): Observable<Ibrides[]> {
return this._http.get<Ibrides[]>(this._brideUrl)
.do(data => console.log('All:' + JSON.stringify(data)))
.catch(this.handleError)
}
private handleError(err: HttpErrorResponse) {
console.log(err.message);
return Observable.throw(err.message);
}
}
this is my component
import { Component, OnInit } from '#angular/core';
import { Ibrides } from "./brides";
import { brideService } from "./brides.service"
#Component({
selector: 'pm-brides',
templateUrl: './brides_list.component.html',
styleUrls: []
})
export class bridesListComponent implements OnInit {
constructor(private _brideService: brideService) {
}
errorMessage: string;
brides: Ibrides[] = [];
ngOnInit(): void {
this._brideService.getBrides()
.subscribe(brides => {
this.brides = brides
},
error => this.errorMessage = <any>error);
}
}
Just reference the file from the root level like this:
_brideUrl = 'app/api/brides.json'
For more information you can refer to this.

Unable to retrieve JSON file in Angular 2 project

I am trying to display static JSON data in my angular 2 project. I am getting a console error 'GET http://localhost:4200/app/data/MOCK_DATA.json 404 (Not Found)' I have added my services.ts and component.ts pages.
service.ts
import { Injectable } from '#angular/core';
import { ConfigurationService } from '../../configuration.service';
import { Http, Response, RequestOptions, Headers } from '#angular/http';
import { Observable } from 'rxjs';
import { ListItem } from './list-item';
#Injectable()
export class DataService {
constructor(
private _http: Http,
private _configurationService: ConfigurationService
) {}
get() : Observable<ListItem[]> {
return this._http.get("app/data/MOCK_DATA.json")
.map((response: Response) => <ListItem[]> response.json())
}
}
app.component.ts
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { DataService } from '../data.service';
import { ListItem } from './list-item';
import { Subscription } from 'rxjs';
#Component({
selector: 'app-component',
templateUrl: 'component.html',
styleUrls: ['component.css']
})
export class Component implements OnInit {
busy:Subscription;
datas: ListItem[] = [];
constructor(
private _dataService: DataService,
private _confirmationService: ConfirmationService,
private _authService: AuthService,
private _router: Router,
) {
}
ngOnInit(){
}
getdatas() {
this.busy =
this._dataService.get()
.subscribe(data => this.datas = data)
}
Since it is static. there is no need to http.get.
Create a json.ts file
export your JSON file as
export const json={
"key":"value"
}
then import it where required
import { json } from './json.ts'
then console.log(json) inside the class to check the file/json.

How to fetch json data in Angular 2+

I'm trying to display a list with data fetched from a local json file. Here is how my service looks so far.
category.service.ts
import { Injectable } from '#angular/core';
import { Http, Response, Headers, RequestOptions } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
#Injectable()
export class CategoryService {
constructor(private _http: Http) { }
getCategories() {
return this._http.get('api/categories.json')
.map((response: Response) => response.json())
.do(data => console.log('All; ' + JSON.stringify(data)))
.catch(this.handleError);
}
private handleError(error: Response) {
console.log(error);
return Observable.throw(error.json().error || 'Server error');
}
}
here is how the Category Menu component where I inject it looks so far
import { Component, OnInit } from '#angular/core';
import { CategoryService } from '../category.service';
#Component({
selector: 'app-category-menu',
templateUrl: './category-menu.component.html',
styleUrls: ['./category-menu.component.css']
})
export class CategoryMenuComponent implements OnInit {
errorMessage: string;
commerceName= `El baratón`;
categoryName = `Bebidas`;
categories: any = 'Not assigned yet';
hasMenu?= true;
constructor(private _categoryService: CategoryService) { }
ngOnInit() {
return this._categoryService.getCategories()
.subscribe(
categories => this.categories = categories,
error => this.errorMessage = error
);
}
}
Now, the error I am getting in the console is a 404. For this project I have used the CLI version 1.0 and the categories.json file inside of the src/api/categories.json folder.
What am I doing wrong here?
move your api/categories.json to assets folder, then change url to
return this._http.get('/assets/api/categories.json')

Categories