-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;
 }
1
  • it is async you cant console outside of subscribe Commented Jun 18, 2020 at 16:00

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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);
});

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.