angular - initialize veriables inside subscribe always undefined angular2 rxjs -
i new angular2 typescript , rxjs , observables .
i trying information api using code
let alertsanswer = this.logservice.getalertsforclient(this.userid); var = alertsanswer.subscribe((response) => { this.alerts=json.parse(response) console.log(this.alerts) //give right response. }, error => { var err = error; alert(err); } )
as can see inside subscribe initialize private variable: "this.alerts"
outside subscribe variable has undefined value console.log(this.alerts) //give undefined.
using this.alert in component doom undefined give error:
<div>{{alerts}}</div>
first question: why ""this.alerts inside subscribe give right value console outside (including doom) undefined.
second question: understand the value coming server async, if have further code relay on answer write it(callback), inside subscribe? meaning of subscribe? help
for first question, this.alerts
right value after subscribe finish
(get data api), use this.alerts
before finished not give right value. should use <div *ngif="alerts">{{alerts}}</div>
make sure data ready use. example, before subscribe finish, use <div>{{alerts.property}}</div>
raise error. console.log
same reason.
for second one, use:
this.logservice.getalertsforclient(this.userid) .subscribe(response => this.alerts = json.parse(response), ()=>console.log('error'), ()=>yourfuncrelayontheresponse(this.alerts));
Comments
Post a Comment