json - Waiting for remote data before rendering in Angular 2 -
i'm trying json data remote server , pass template page
object.
but when try value of page.name
inside template, getting error says:
cannot read property 'name' of undefined
on other hand, console.log
shows correct data coming server.
looks like, render process doesn't wait data received first.
what doing wrong?
here .ts
files:
app.component.ts
import {component, oninit} '@angular/core'; import {pageservice} './page.service'; import {page} './page'; @component({ selector: 'app-root', templateurl: './app.component.html', providers: [pageservice] }) export class appcomponent implements oninit { page: page; constructor(private pagesrv: pageservice) { } ngoninit(): void { this.pagesrv.getdata(2802).then((result) => { this.page = result; console.log(this.page); }); } }
page.service.ts
import {injectable} '@angular/core'; import {http} '@angular/http'; import 'rxjs/add/operator/topromise'; import {page} './page'; @injectable() export class pageservice { constructor(private http: http) { } getdata(id: number): promise<page> { return this.http.get('http://example.com/items/' + id + '?expand=categories,comments,modifications,tags,media,filefields') .topromise() .then(response => response.json() page) .catch(this.handleerror); } private handleerror(error: any): promise<any> { console.error('an error occurred', error); // demo purposes return promise.reject(error.message || error); } }
page.ts
export class page { id: number; slug: string; name: string; sell_price: string; details: string; excerpt: string; imguri: string; created_at: string; rating: number; categories: array<any>; comments: array<any>; media: array<any>; tags: array<any>; }
initialize page
variable empty object.
Comments
Post a Comment