Cannot Access Data in Angular Components - json

problem
Cannot Access Data from Symfony to Angular2 Component.
what i tried
Angular2 snippet
dashboard.component.ts
import { Component, OnInit } from '#angular/core';
import { Hero } from '../hero';
import { HeroService } from '../hero.service';
import { Http, Response, Headers, RequestOptions } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
#Component({
selector: 'app-dashboard',
moduleId: module.id,
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
constructor(public http: Http) {}
ngOnInit() {
}
public persons: any;
data() {
this.http.get('http://localhost/api')
.map((res: Response) => res.json())
.subscribe((res: any) => {
this.persons = res;
});
}
}
dashboard.component.html
<a *ngFor="let person of persons" [routerLink]="['/detail', hero.id]" class="col-1-4">
<div class="module hero">
<h4>{{person.name}}</h4>
</div>
</a>
</div>
json data
{
id: "592413bc93d2992800000029",
name: "A Foo Bar",
price: 19.99
},
{
id: "5924145b93d299a812000029",
name: "A Foo Bar",
price: 19.99
}
we have backend as symfony2 we are just passing json into component.
when i tried to print {{persons}} in dashboard.component.html file it doesn't print something.
can anyone suggest what im missing while rendering data from rest api.
any suggestion is most welcome.
i have found problem no Http Request were Triggered in Browser when data() function triggered by angular2 component.

you need to call the data method. Otherwise, http request will not trigger.
constructor(public http: Http) {
this.data();
}

i have fixed the problem
they are 2 issue in in_memory_api or fake-bakend was main problem
app.module.ts
imports:
[
InMemoryWebApiModule.forRoot(InMemoryDataService)
]
instead try with:
imports:
[
InMemoryWebApiModule.forRoot(InMemoryDataService, {passThruUnknownUrl: true}), // fake in memory API simulation
]
if you use fake provider
providers: [
fakeBackendProvider,//comment this,if you use this xhr request would go 404
]
service.ts
private headers = new Headers({'Content-Type': 'application/json','Access-Control-Allow-Origin':'*'});
private heroesUrl = 'http://localhost/api';
getApiData(): Promise<ApiDashboard[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json() as ApiDashboard[])
.catch(this.handleError);
}
try these step im sure this will works if http request gets 404.

Also it seems your router link is wrong in the HTML. SHouldn't it be
[routerLink]="['/detail', person.id]" ?

Related

IONIC API Undefined

I have an IONIC APP with CORDOVA. I Just want to GET a JSON from an URL.
I Created a service call rest.service.ts
rest.service.ts
import { Injectable } from '#angular/core';
import { HTTP } from '#ionic-native/http/ngx';
#Injectable({
providedIn: 'root'
})
export class RestService {
BASE_URL = 'http://whatever.....';
constructor(public http: HTTP) {}
getProjects() {
const URL = this.BASE_URL + 'getProjects';
this.http.get(URL, {}, { 'Content-Type': 'application/json' })
.then(answer => {
return JSON.parse(answer.data);
})
.catch(error => {
console.log(error.status);
console.log(error.error); // error message as string
console.log(error.headers);
});
}
}
Here in this file I can see the info. If I insert something like...
console.log(JSON.parse(answer.data));
I can see the results in JSON just as I Want.
The problem is when I try to use this methods in other files...
otherpage.page.ts
import { Platform } from '#ionic/angular';
import { RestService } from './../rest.service';
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-otherpage',
templateUrl: './otheropage .page.html',
styleUrls: ['./otherpage .page.scss']
})
export class OtherPage implements OnInit {
projects;
constructor(
public platform: Platform,
public rest: RestService,
) {
this.projects = this.rest.getProjects();
console.log(this.projects); // UNDEFINED
}
ngOnInit() { }
}
Here... this.projects... is undefined... ¿What is happening? I tried platform.ready, insert in ngOnInit... nothing works.
You need to modify the service and subscribe this service your page.
BASE_URL = 'http://whatever.....';
getProjects() {
const URL = this.BASE_URL + 'getProjects';
return this.http.get(URL, {}, { 'Content-Type': 'application/json' });
}
Subscribe this service observable in your page.ts file.
this.rest.getProjects().subscribe((answer)=>{
this.projects = JSON.parse(answer.data);
console.log(this.projects); // here you get the json
},error=>{
consoole.log(error)
});
Note:
console.log(this.projects); // UNDEFINED
Because this line executes before the http observable send the response, you need to subscribe that http observable to get the json.

Angular 2 NFor loop not displaying

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 :)

Angular2 - cannot display json objects

my boss decided to implement Angular2 into our project. I'm preety new to this technology. I'm trying to display JSON from url, but the result is not as I expected. *ngFor doesn't display any data.
This is the code:
vehicle.service.ts
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class VehicleService {
constructor(private http: Http){ }
getVehicle() {
return this.http.get('https://jsonplaceholder.typicode.com/posts')
.map(res => res.json());
}}
vehicle.component.ts
import { Component } from '#angular/core';
import { VehicleService } from './vehicle.service';
#Component({
moduleId: module.id,
selector: 'vehicle-json',
templateUrl: 'vehicle.html',
providers: [ VehicleService ]
})
export class VehicleComponent {
vehicle: Vehicle[];
constructor(private vehicleService: VehicleService){
this.vehicleService.getVehicle().subscribe(vehicle => {
/*console.log(vehicle);*/this.vehicle = vehicle;
});
}
}
interface Vehicle {
id: number;
title: string;
body: string;
}
vehicle.html
<div *ngFor="let vehicle of vehicles">
<h3>{{vehicle.title}}</h3>
<p>{{vehicle.body}}</p>
</div>
test 1-2-3
The output is: "test 1-2-3". I checked if the jsons will be displayed inside the console using: console.log(vehicle); - it worked, it returns Array of Objects.
What am I doing wrong? Any ideas how to fix my code?
You have an error:
this.vehicleService.getVehicle().subscribe(vehicle => {
this.vehicle = vehicle;
})
but in your html you refer to let vechicle of vehicles
You should add an "s" to your this.vehicle to your subscription like so:
this.vehicleService.getVehicle().subscribe(vehicle => {
this.vehicles = vehicle;
})
Edit: Just forgot to meantion to change the local variable vehicle: Vehicle[] to vechicles: Vehicle, but that you figured out that yourself! ;)

angular2 rxjs .map does't work in version 2.0.1

This code works on angular2 v.2.0.0 .rc.2 but does't on angular2 v2.0.1
app.appcomponent.ts
import { Component, OnInit } from "#angular/core";
import { Injectable } from '#angular/core';
import { Http, Response, URLSearchParams } from "#angular/http";
import { IFood } from "./food";
import { Headers, RequestOptions } from "#angular/http";
I can import this for use .map right?
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/catch';
#Component({
selector: "my-app",
template: `
<h1>My First Angular 2 App</h1>
<ul *ngFor='let food of foods'>
<li>{{food.foodName}}</li>
</ul>
`,
templateUrl: "./app/form.html"
})
#Injectable()
export class AppComponent implements OnInit {
public values: string[];
public headers: Headers;
errorMessage: string;
I have a list of food in my controller, foodid, foodname
foods: IFood[];
foodModel = <IFood>{};
constructor(private http: Http) {
this.http = http;
this.headers = new Headers();
this.headers.append("Content-Type", "application/json");
}
ngOnInit() {
return this.http.get("/home/getdata")
there's .map does't work, can't we use .map in angular2 2.0.1?
.map((response: Response) => <IFood[]>response.json())
.subscribe(data => this.foods = data, error =>
this.errorMessage = <any>error);
}
}
Do I need to create Services?
How to fix this, thank you
Try updating to Typescript 2.0.3
This solved the issue for me.
And make sure you are using ECMAScript 6

Output array values to template

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.