angular - Subscribe in angular2 -
in project have service call use in multiple components.is there way have separate method in service save data , call method data.the first method below service call reusable data , second method 1 call data.but returns undefined each time use it.help please!!!
getuserroles(): observable<loggedinuserdetails> { return this.http.get(baseurl + getuserrole).map((res: response) => { var data = res.json(); this.loggedinuser = data; return this.loggedinuser; }) } getuserdetails() { return this.loggedinuser; }
component using above methods
export class intiatedtravelsummarycomponent implements oninit { public loggedinuser: loggedinuserdetails; public id:number intiatedtravelrequestdetail: travelreqform; test:travelreqform[]; test2:travelreqform[]; constructor(private neutravelservice: neutravelservice,private route:activatedroute) { this.id =route.snapshot.params['travellerid']; } ngoninit() { this.loggedinuser =this.neutravelservice.getuserdetails(); this.neutravelservice.getintiatedtraveldetails(this.loggedinuser).subscribe(data =>{ this.test = data; this.intiatedtravelrequestdetail= this.neutravelservice.gettravelsummarydetails(this.id,this.test); console.log(this.intiatedtravelrequestdetail); }); } }
update* or if can tell me how pass data synchronously view. i.e this.intiatedtravelrequestdetail shows value within service call shows undefined after call. if can tell me how render view after data loaded
ngoninit() { this.neutravelservice.getuserroles().subscribe(data => { this.loggedinuser = data; this.neutravelservice.getintiatedtraveldetails(this.loggedinuser).subscribe(data =>{ this.test = data; this.intiatedtravelrequestdetail= this.neutravelservice.gettravelsummarydetails(this.id,this.test); console.log(this.intiatedtravelrequestdetail); }); }); console.log(this.intiatedtravelrequestdetail); } }
as noticed intiatedtravelrequestdetail
undefined outside callback, here excellent answer you, written our sir mr. @echonax :) : how return response observable/http/async call in angular2?
this asynchronous event causes view rendered before data has been retrieved. since not providing sample of template, i'm guessing this.intiatedtravelrequestdetail
object , want display properties this.
you use safe navigation operator, i.e ?
{{intiatedtravelrequestdetail?.myproperty}}
this safeguards null values.
also wrap it inside *ngif
<div *ngif="intiatedtravelrequestdetail"> {{intiatedtravelrequestdetail.myproperty}} </div>
which won't render part of view unless there values in intiatedtravelrequestdetail
.
hope helps! :)
Comments
Post a Comment