Fetching a json file in Angular 2 [duplicate] - javascript

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) => {
}

Related

angular2 sharing data between components , getters and setters [duplicate]

This question already has answers here:
Angular2 - Share data between components using services
(3 answers)
Closed 5 years ago.
I have a question identical to this guy here:
Angular 2 Setter and Getter
The solution que provided thought is not enough for my project to work so I'll explain my situation with some more details to see if you guys can help me!
I have a service dataBase.service.ts :
import {Injectable} from "#angular/core";
#Injectable()
export class dataBaseService{
serviceData: string;
get data():string{
return this.serviceData;
}
set data(value:string){
this.serviceData = value;
}
}
this service is obviously added to app.module.ts as a provider..
on my component A i have:
import { Component, OnInit } from '#angular/core';
import {dataBaseService} from "../dataBase.service";
#Component({
selector: 'app-tipo',
templateUrl: './tipo.component.html',
styleUrls: ['./tipo.component.scss'],
providers: [dataBaseService]
})
export class A implements OnInit {
constructor( public dataService:dataBaseService) {
this.dataService.serviceData = 'hello';
}
ngOnInit() {
console.log(this.dataService.serviceData);
}
}
Until Here everything is fine. If I show on console:
console.log(this.dataService.serviceData); it returns me "hello" as expected
but on my next component when I print again the same data it shows undefinied:
import { Component, OnInit } from '#angular/core';
import {dataBaseService} from "../dataBase.service";
#Component({
selector: 'app-modelo',
templateUrl: './modelo.component.html',
styleUrls: ['./modelo.component.scss'],
providers: [dataBaseService]
})
export class ModeloComponent implements OnInit {
ngOnInit() {
console.log(this.dataService.serviceData);
}
constructor(public dataService: dataBaseService) {
}
}
console.log(this.dataService.serviceData); it returns "undefined"..
So how can I save that data that I putted on the first component and beeing able to show it on another component? what am I missing?
UPDATE:
Some people like me didn't find an answer to the other question like this one on stack and that's because Instead of adding the providers individually you have to add them globably (on module.ts) !!!!!!!!!!!!
As you said you have already added the provider on the module level,try commenting out the providers declaration from components.

Fetch the data from GITHUB API

I want to get all the data from github API. But it doesn't work for me.
My .ts file is below:
import { Component } from '#angular/core';
import { GitTakeService } from "app/git-take.service";
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
user:any;
constructor(private gittakeService:GitTakeService ){
this.gittakeService.getUser().subscribe(user=>{
debugger;
this.user=user;
console.log(user);
})
}
}
My service is below:
import { Injectable } from '#angular/core';
import {Http,Response, Headers} from '#angular/http'
import'rxjs/add/operator/map';
#Injectable()
export class GitTakeService {
constructor(private http:Http) { }
getUser(){
debugger;
return this.http.get("http://api.github.com/users")
.map(
(resp:Response)=>{
return resp.json().response;
}
);
}
}
When consoling the user in .ts file, it shows undefined. My view file is like this:
{{user}}
Anyone please help me to solve this problem?
What you are receiving is an array, so you want to use resp.json() instead of resp.json().response there is no such property like response in your response. So your map should look like this:
getUser(){
debugger;
return this.http.get("http://api.github.com/users")
.map((resp:Response)=>{
return resp.json();
});
}
and in your component I would name the array users instead of user, since there are several users in your response. Also I suggest you keep anything unnecessary from the constructor and use OnInit instead:
users = [];
constructor(private gittakeService:GitTakeService ){ }
ngOnInit() {
this.gittakeService.getUser()
.subscribe(data => {
this.users = data;
});
}
Then you can iterate the array and use the property names to show the properties of one user object:
<div *ngFor="let user of users">
{{user.login}}
</div>
resp.json().response is undefined resp.json() is what you want
the service function:
getUser(){
return this.http.get("http://api.github.com/users")
.map(
(resp:Response)=>{
return resp.json();
}
);
}`
and the component:
this.gittakeService.getUser().subscribe(users=>{
this.user=users[0];
console.log(user);
})

Observables with angular 2 isn't working (Http method)

I'm having trouble with my service. I have a service wich get a JSON from the HTTP module and fill a class 'olders' with it. But when I call my service, it doesn't do anything and my class olders is still undifined...
And if I make a *ngFor directive in the yearbook.component.html, I just get nothing...
I think my problem came from my service, but I don't know where is the error...
Even if i put the console.log inside of the subscribe
my yearbook.component :
import {Component} from '#angular/core'
import {Olders} from './olders'
import {OldersService} from './olders.service'
#Component({
moduleId: module.id,
selector: 'yearbook',
templateUrl: 'yearbook.component.html',
})
export class YearbookComponent {
olders : Olders[];
constructor(
private _oldersService : OldersService
){}
ngOnInit() {
this._oldersService.getOldersfromAPI()
.subscribe( res => {this.olders = res,
console.log(this.olders)},
err => console.error(err.status)
);
}
}
and the olders.service :
import {Injectable} from '#angular/core'
import {Http} from '#angular/http'
import {Olders} from './olders'
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/do'
#Injectable ()
export class OldersService {
constructor(private _http:Http) {
}
getOldersfromAPI(){
return this._http.get('../CDN/olders.json')
.do(x => console.log(x))
.map(olders => {olders = olders.json()});
}
}
Thanks in advance for all your answers guys
You are missing a return statement in your mapping:
.map(olders => {olders = olders.json()});
should be:
.map(olders => { return olders = olders.json()});

getting json data into an array angular2

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.

Ionic2, Angular2, HTTP and Observables

After reading almost everything I found about observables, I still don't understand pretty well how they work.
I am doing the http request here:
import { Component, OnInit, Injectable } from '#angular/core';
import { Http, Response, Headers, RequestOptions } from '#angular/http';
import { NavController } from 'ionic-angular';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
#Injectable()
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
webs: any;
getWebs(): any{
return this.http.get( 'here the url' )
.map((res: Response) => res.json());
}
constructor(public navCtrl: NavController, private http: Http) {}
ngOnInit(){
this.getWebs().subscribe(response => {
this.webs = response;
console.log(this.webs);
});
}
}
On the console, this.webs is correctly printed. That means, the get request ist working fine and I am retrieving the object I want. That is a normal JSON object.
The problem is, on the view, if I try to print some property of the object (the same properties I see on the console) like that
{{ webs.name }}
I get the whole time that error:
Error in ./HomePage class HomePage - caused by: Cannot read property 'name' of undefined
That was sooo easy with Angular 1 :( I already read a lot of tutorials but I can't find any answer to my problem.
Thanks for your help.
The view is shown before the http response is returned.
{{webs?.name}}
should work.
Or do this.webs=getWebs()
and {{webs.name | async}}
It should be something
this.getWebs().then((webs) => {
webs.subscribe(response => {
this.webs = response;
resolve(webs);
console.log(this.webs);
});
})
so after you getWebs do this.This is untested code but you get the logic.
You are calling before you get data.
ngOnInit(){
return new Promise(resolve => {
this.http.get('webs.json')
.map(res => res.json())
.subscribe(webs => {
this.webs = webs;
resolve(this.webs);
});
});
}

Categories

Resources