Reputation: 19587
I am new to angular2 typescript and rxjs and observables .
I am trying to get information from api using this code
let Alertsanswer = this.LogService.getAlertsForClient(this.userId);
var a = Alertsanswer.subscribe((response) => {
this.alerts=JSON.parse(response)
console.log(this.alerts) //give the right response.
},
error => {
var err = error;
alert(err);
}
)
as you can see inside the subscribe I initialize a private variable: "this.alerts"
outside the subscribe this variable has undefined value console.log(this.alerts) //give undefined.
Using this.alert in component doom is undefined too this give an error:
<div>{{alerts}}</div>
first question: why ""this.alerts inside subscribe give right value to the console but outside (including the doom) is always undefined.
second question: I understand the the value coming from the server is async, if I have further code that relay on the answer where would I write it(callback), would it be inside the subscribe? what is the meaning of subscribe? thanks for any help
Upvotes: 4
Views: 5703
Reputation: 2253
for your first question, this.alerts
get the right value after subscribe finish
(get the data from api), use this.alerts
before it finished will not give the right value. you should use <div *ngIf="alerts">{{alerts}}</div>
to make sure the data is ready for use. for example, before subscribe finish, use <div>{{alerts.property}}</div>
will be raise an error. console.log
is the same reason.
for your second one, use:
this.LogService.getAlertsForClient(this.userId)
.subscribe(response => this.alerts = JSON.parse(response),
()=>console.log('error'),
()=>yourFuncRelayOnTheResponse(this.alerts));
Upvotes: 2
Reputation: 2034
Hey you are doing some wonky stuff by assigning services into variables. Have edited you code a bit to show you how I would define things:
export class LoginComponent
{
private alerts; //This needs to be defined here on the class first
constructor(public loginService: LoginService)
{
}
ngOnInit()
{
this.LogService
.getAlertsForClient(this.userId)
.subscribe(response =>
{
this.alerts = JSON.parse(response); // Assign response to class member alerts.
},
error=>
{
console.log(error);
})
}
}
Upvotes: 0