getting json data into an array angular2 - javascript

I am not sure what i am missing from my code but currently i am not presented with any errors when i run it but i am also not seeing the results that i am expecting. I have a json file that i am loading into an array and would like to loop through that array and display parts of its data onto the page.
Here is what i have so far:
Service file
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
#Injectable()
export class AddressDataService{
addressData: Array<any>;
constructor(private http:Http){ }
getAddressData(){
return this.http.get('./api/addressData.json')
.map((res:Response) => res.json());
}
}
JSON File
[{
"type": "home",
"id": 1
}, {
"type": "apartment",
"id": 2
}, {
"type": "homeless",
"id": 3
}]
Component File
import { Http } from '#angular/http';
import { AddressDataService } from './address.service';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
#Component({
selector: 'my-app',
templateUrl: '....',
styleUrls: ['./styles.css'],
providers: [AddressDataService]
})
constructor(private addressDataService: AddressDataService) {}
addressData = [];
getAddressData() {
this.addressDataService.getAddressData()
.subscribe(data => this.addressData = data);
}
HTML File
<div *ngFor="let addressDetail of addressData">
{{addressDetail.type}}
</div>
Am i doing this the right way?

You need to call your getAddressData for example in your OnInit, I assume you want to fetch the data when navigated to page.
So:
ngOnInit() {
this.getAddressData();
}
When this is handled, you will face another issue. Http-requests don't allow relative paths, so
return this.http.get('./api/addressData.json')
will cause an error, you need to replace the dot in your "url" with the actual complete path for the json file, starting from the top level folder.

In your component file:
.subscribe(
data => {
const helperArray = [];
for (let key in data) {
helperArray.push(data[key]);
}
}
);

Something in your component class needs to call your getAddressData method. Either the constructor, or a better option is to implement OnInit and call it from there.

Related

How do I get data to display in Angular from API in Express?

I am trying to use Nodejs/Express as my back end for producing data from a database. I currently have an api route setup so that a database query will result in its directory. So if I visit localhost:3000/api currently I will see the following:
{"status":200,"data":[{"Issuer_Id":1,"Data_Id":2,"Data_Name":"Name 1"},{"Issuer_Id":2,"Data_Id":14,"Data_Name":"Name 2"},{"Issuer_Id":2,"Data_Id":1,"Data_Name":"Name 3"}],"message":null}
This leads me to believe I have everything setup correctly on the back end.
Now how do I get this data to display on my Angular front end?
I have been through hours of tutorials and this is what I have come up with:
nav.component.ts
import { Component, OnInit } from '#angular/core';
import { DataService } from '../../data.service';
import { Series } from '../../data.service';
import {Observable} from 'rxjs/Rx';
#Component({
selector: 'app-fixed-nav',
templateUrl: './fixed-nav.component.html',
styleUrls: ['./fixed-nav.component.css']
})
export class FixedNavComponent implements OnInit{
serieses: Series[] ;
constructor(private dataService: DataService) {}
ngOnInit() {
this.dataService.getSeries().subscribe((serieses: Series[]) => this.serieses = serieses);
}
}
data.service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from'#angular/common/http';
import { Http, Headers, RequestOptions, Response } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/toPromise';
export class Series {
Issuer_Id: number;
Data_Id: number;
Data_Name: string;
}
#Injectable()
export class DataService {
constructor(private _http: Http) {}
getSeries(): Observable<Series[]> {
return this._http.get("http://localhost:3000/api/")
.map((res: Response) => res.json());
}
}
app.module.ts
import { Form1Module } from './modules/form1/form1.module';
import { FixedNavModule } from './modules/fixed-nav/fixed-nav.module';
import { HeaderModule } from './modules/header/header.module';
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { NgbModule } from '#ng-bootstrap/ng-bootstrap';
import { AppComponent } from './app.component';
import { HttpClientModule } from '#angular/common/http';
import { HttpModule } from '#angular/http';
import { DataService } from './data.service';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpModule,
HttpClientModule,
HeaderModule,
FixedNavModule,
Form1Module,
NgbModule.forRoot()
],
providers: [DataService],
bootstrap: [AppComponent]
})
export class AppModule { }
What do I need to enter in the nav.component.html to see the results?
Also note that when I refresh my angular page on lcoalhost:4200 I can see that the GET request is hitting the /apiu/ on the 3000 express server.
I am trying to help with best practices which might help get the intended result. I will amend this answer as we troubleshoot and hopefully arrive at the right answer.
So in your dataServices service I wanted to point out a couple things. Angular recommends we use the httpClient and not http and warn that http will soon be depreciated. I am fairly new to angular myself and have only ever used httpClient and have gotten great results so I recommend using that. I think this means that the promise that you are returned is changed too. Namely, you pust use a .pipe method inorder to use rxjs operators like map on the result. So this is what your dataService file would look like:
import { Injectable } from '#angular/core';
import { HttpClient } from'#angular/common/http';
import { Http, Headers, RequestOptions, Response } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import { map } from 'rxjs/operators';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/toPromise';
export class Series {
Issuer_Id: number;
Data_Id: number;
Data_Name: string;
}
#Injectable()
export class DataService {
constructor(private _http: HttpClient) {}
getSeries(): Observable<Series[]> {
return this._http.get<Series[]>("http://localhost:3000/api/")
.pipe(
map((res) => {
console.log(res);
return <Series[]> res
})
)
}
}
Note that I have imported map in a different rxjs/operators.
In actuality you dont even need to pipe or map the return since you have already declared the type of return in the get method of _http. HttpClient will cast the return into a Series[] for you so this one liner: return this._http.get("http://localhost:3000/api/") would work. I've written the code how it is however to console.log the return that your getting.
In the comments, could you tell me what is logged?
I am unable to correct your code I am providing my own setup Works for Me
In server.js
module.exports.SimpleMessage = 'Hello world';
Now in App.js
var backend = require('./server.js');
console.log(backend.SimpleMessage);
var data = backend.simpleMessage
In index html include App.js
<script src = '/App.js'></script>
alert(simpleMessage)
And you should get 'hello world'

Angular 2 Error: (SystemJS) Can't resolve all parameters for Component Service: (?)

I tried to call the web API from my Angular2 Component service in Visual Studio, but continuously I am getting the error like "(SystemJS) Can't resolve all parameters for anniversary service: (?)".
My sample application is working fine if I remove my component service.
ComponentService:
import { Injectable } from '#angular/core';
import {Http, Response } from '#angular/http';
import { IData } from '../Common/details';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
export class AniversaryService {
constructor(private _http:Http) { }
getImages(): Observable<IData[]> {
return this._http.get("/api/ImageService/Details")
.map((response: Response) => <IData[]>response.json()
};
}
and my Corresponding Component:
import { Component, OnInit } from '#angular/core';
import { DomSanitizer } from '#angular/platform-browser';
import { IData } from '../Common/details';
import { AniversaryService } from './Aniversary.service';
#Component({
selector: 'my-AniversaryComponent',
providers: [AniversaryService]
})
export class AniversaryComponent implements OnInit {
data: IData[];
constructor(private _aniversaryservice: AniversaryService) { }
ngOnInit() {
this._aniversaryservice.getImages().subscribe((details) => this.data
=details);
}
}
}
I tried different solutions from stack overflow but nothing works for me.
Please help me to overcome this problem.
Thanks in Advance for the help
The service appears to be missing the #Injectable decorator.

How to load this JSON data into Angular2

Im new to Angular2, I want to load this Json data and display in a page, Im not sure how to do..? From all sources I learnt I made a code and attached it below, But its not running because of some errors, can anyone help in fixing or writing a new code for me so that i can learn from it..
Thanks in advance for the help.
My code file - student.json
[
{
"name": "John",
"id_number": "12",
"attendance": "276 days",
"grade": "A"
},
],
this is my students.service.ts code
import {Injectable} from '#angular/core';
import { Http, Response } from '#angular/http';
#Injectable()
export class StudentsService {
constructor(private http:Http)
{
}
getStudents() {
return this.http.get('./students.json')
.map((response: Response) => {
console.log("mock data" + response.json());
return response.json();
}
}
and, this is my students.component.ts file
import {Component} from '#angular/core';
import { Http, Response } from '#angular/http';
import {StudentsService} from './students.service';
import 'rxjs/add/operator/map'
import 'rxjs/Rx';
#Component({
selector: 'students',
templateUrl: 'students.html',
styleUrls: ['./students.scss']
})
export class students {
public students;
constructor( private _studentsService:StudentsService, private http:Http)
{
this.students = this._studentsService.getStudents();
}
ngOnInit() {
this._load();
}
private _load() {
this.students = this._studentsService.getStudents();
}
}
You can write a service to load your html from json file and available all over your application like below.
#Injectable()
export class ConfigService {
public config: any;
private configObs: Observable<any>;
constructor(private http: Http) {
}
public load(filename: string): Observable<any> {
if ( this.config ) {
return Observable.of(this.config);
} else {
this.configObs = this.http.get(filename).map((res) => {
this.config = this.config || res.json() || {};
return this.config;
});
}
return this.configObs;
}
}
You can also put your data in typescript class format if that option is available referance answer
If you have JSON data and you want to show it in page.
Use Data Table to show It.
Here is the example you can see how to show on page.
Please click Here
Assign our json to a varible
myData = [{
"name": "John",
"id_number": "12",
"attendance": "276 days",
"grade": "A"
},
...
...
],
In your Html
<ul>
<li *ngFor="let data of myData">
<div>{{data.name}}</div>
<div>{{data.id_number}}</div>
<div>{{data.attendance}}</div>
<div>{{data.grade}}</div>
</li>
</ul>
Hope it helps
What you are dealing with is an Observable students, either you need to manually subscribe to that observable, or use the async pipe in the template which handles the subscribing for your.
Also you are now performing the request twice, in the constructor and in your OnInit. Remove one of those, I'd remove the one in the constructor, since I like to keep everything away from the constructor, that does not need to be there, like mentioned here: https://stackoverflow.com/a/35763811/6294072
Back to the subscribing... either do:
this.students = this._studentsService.getStudents();
<div *ngFor="let student of students | async">
<p>{{student.name}}</p>
<!-- ... -->
</div>
or:
this._studentsService.getStudents()
.subscribe(students => {
this.students = students;
})
<div *ngFor="let student of students">
<p>{{student.name}}</p>
<!-- ... -->
</div>

Fetching a json file in Angular 2 [duplicate]

This question already has answers here:
How to get a json file in Angular 2 using the Http class?
(3 answers)
Closed 6 years ago.
There are few solutions on SO, but apparently they are deprecated. Angular 2 changes all the time...
Im trying to fetch a json file to my file.
There's a items.json file.
I'm wondering if I am able to make this work in just one file? I mean, just inside the app.component.ts? app.component.ts file actually looks like:
import { Component } from '#angular/core';
import { Http } from '#angular/http';
import { Injectable } from '#angular/core';
#Component({
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
#Injectable()
export class AppServices{
constructor(private http: Http) {
let obj;
this.getJSON().subscribe(data => obj=data, error => console.log(error));
}
public getJSON(): {
return this.http.get("./items.json")
.map((res:any) => res.json())
}
}
export class AppComponent {
let items = getJSON();
}
}
Or maybe I have to include a app.service.ts file? And drop there the code fetching the json? It was so easy to do it in Angular1, why they made this so complicated...
I'm looking for the shortest solution as it is possible I will upvote every answer. Thank u in advance
EDIT
I got another code:
import { Component } from '#angular/core';
import { Http } from '#angular/http';
#Component({
selector: 'watchlist',
templateUrl: './watchlist.component.html',
styleUrls: ['./watchlist.component.css']
})
export class WatchlistComponent {
data;
constructor(private http:Http) {
this.http.get('items.json')
.subscribe(res => this.data = res.json());
}
}
How to load this data into my items variable?
// A function You can declare an app
app() {
return this.http.get('/config.json');
}
this.app().subscribe((data: any) => {
}

can't access a returned object properties from a service by angular 2 data binding

Process
I am using a service to get data (objects) from a json file with an observable and display them in the HTML template.
Problem
I can't access the objects properties by using {{obj.prop}}, it throws an error "Cannot read property 'prop' of undefined".
However if I try to access it in the component, it works.
Code
ContentService
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/Rx';
#Injectable()
export class ComponentContentService {
constructor(private _http: Http) { }
getContent() {
return this._http
.get('./app/services/dataContent.json')
.map((response:Response) => response.json())
.do(response => console.log('response = ', response))
}
}
TopContentComponent
import { Component } from '#angular/core';
import { WowComponent } from '../libraries.components/wow.component/wow.component';
import { BackstretchComponent } from '../libraries.components/backstretch.component/jquery.backstretch.component';
import { ComponentContentService } from '../services/component.content.service';
#Component({
selector: 'top-content',
templateUrl: './app/top-content.component/top-content.component.html',
directives: [WowComponent, BackstretchComponent]
})
export class TopContentComponent {
header : any;
description : any;
data : any;
constructor(private _ComponentContentService: ComponentContentService) {}
ngOnInit() {this.getComponentContent();}
getComponentContent() {
this._ComponentContentService.getContent()
.subscribe(
(data) => {
this.data = data;
}
);
}
}
Template
<p>{{data.header.title}}<p>
JSON
{
"header" : {
"title":"Our New Course is Ready",
"description" : "We have been working very hard"
},
"Footer" : {
"title":"Our New Course is Ready",
"description" : "We have been working very hard to create the new version of our course. It comes with a lot of new features, easy to follow videos and images. Check it out now!"
},
}
You should change {{data.header.title}} for {{data?.header?.title}}

Categories

Resources