-4

EDIT: Sorry everbody, I did google it at first of course but couldn't find a satisfying answer. Thank you all for the fast help.

short Problem: I have an Angular component which gets data from a server on button press from the submitted values. This data should be passed onto the next component via a Service. However this doesn't seem to work synchroniously. If I press the add button console.log(this.jsonData) outputs nothing. When I press it a second time the correct data from the server is shown.

This must have something to do with Angular but I can't figure out why this happens. I hope somebody has experienced something similar and can help with this. Thanks!

HTML:

 <form>
      <input #userName type="text" required>
      <input #seqNumber type="number" min="1" max="70">
 </form>
<button (click)="add(userName.value, seqNumber.value);">
  add
</button>

component.ts

add(name: string, seqNum: string): void {

this.inputUser = name;
this.seqNumber = seqNum;

this.loginService.getSequence(name, seqNum)
.subscribe(data => this.jsonData = data);
console.log(this.jsonData);
}

and service.ts

 // fetches sequence from server
getSequence(userId: string, sessionNum: string): any {

 const options = { 
  params: new HttpParams()
  .set('userId', userId)
  .set('sessionNum', sessionNum)};

  const sequence = this.http.get<Sequence[]>(this.loginUrl, options);
  return sequence;
 }

2 Answers2

1

The data is assigned asynchronously. The this.jsonData variable is still undefined when it's accessed. Any statements that directly depend on the this.jsonData should be inside the subscription.

this.loginService.getSequence(name, seqNum).subscribe(
  data => { 
    this.jsonData = data;
    console.log(this.jsonData);
  },
  error => {
    // always good practice to handle HTTP erros
  }
);

More info on how to access asynchronous data here.

ruth
  • 29,535
  • 4
  • 30
  • 57
0

Subscribe is a asynchronous operator, if you will print jsondata inside subscribe you will get it in first click like below. Actually it prints even before getting data if you keep it outside subscribe. the code inside subscribe only gets invoked once response is there. it will not wait till response is received for executing console.log if you keep it outside susbcribe.

add(name: string, seqNum: string): void {

this.inputUser = name;
this.seqNumber = seqNum;
this.loginService.getSequence(name, seqNum)
.subscribe(data => {
    this.jsonData = data;
    console.log(this.jsonData);
});

}
Aakash Garg
  • 10,649
  • 2
  • 7
  • 25