angular - Angular2 - Waiting for observable to return with data -
angular2 templates seem fine waiting list return observable this:
<li *ngfor="let product of products"> {{product.displayproductname}} </li> ... export class publicproductlistcomponent { errormessage: string; products: products[]; mode = 'observable'; constructor(private productservice: productservice) { } ngoninit() { this.getpublicproducts(); } getpublicproducts() { this.productservice.getpublic() .subscribe( products => this.products = products, error => this.errormessage = <any>error); } }
but when tried same thing object (userdash
), got errors saying object undefined because wasn't waiting subscription find data:
<li *ngfor="let prod of userdash.ownedproducts"> {{prod.displayproductname}} </li> ... export class ownedproductlistcomponent { errormessage: string; userdash: userdashboard; mode = 'observable'; constructor(private userservice: userservice) { } ngoninit() { this.getuserdashboard(); } getuserdashboard() { this.userservice.getuserdashboard() .subscribe( dashboard => this.userdash = dashboard, error => this.errormessage = <any>error); } }
doing null/undefined check seems work can't figure out if it's angular way it.
<ul *ngif="userdash"> <li *ngfor="let dash of userdash.ownedproducts"> {{dash.displayproductname}} </li> </ul>
i'm still brand new trying learn pattern, please forgive ignorance.
edit --- here's code getuserdashboard()
getuserdashboard(): observable<userdashboard> { return this.http.get(sitesettings.apiurl + "user/" + this.authservice.getclientid() + "/dashboard", this.authservice.getauthorizationheaders()) .map(function (res: response) { let body = res.json(); return body; }) .catch(this.handleerror); }
try creating object in constructor.
in ownedproductlistcomponent.ts
constructor(private userservice: userservice) { this.userdash = new userdashboard(); }
in userdashboard model class
export class userdashboard{ constructor() { this.ownedproducts = new products() } }
Comments
Post a Comment