2

I have the following issue: I have a http.post request to get json data from the server. It excecutes properly and when I log this.data in this method I get the required data. However, once I try to call this data, the method does not seem to fill it the way it should. I figured this much out, but not why or how to solve this.

authenticate(username, password) {
    var creds = JSON.stringify({ 
      UserName: username.value, 
      UserPassword: password.value, 
      SetDebug: true
    });

    var headers = new Headers();

    headers.append('Content-Type', 'application/json');

    // SERVER
    this.http.post('http://demo/aariworx5/api/login/login', creds ,{headers: headers})
    .subscribe(
    res => {
        this.data = res.json();
    },

    error => console.log(error)
    );
  }
JanVanHaudt
  • 253
  • 1
  • 6
  • 16

1 Answers1

2

I guess you access this.data before it is set. subscribe(...) executes eventually but Angular2 moves on executing other things while the request to the server is made.

Your question doesn't provide enough information to give more detailed guidance how to solve the problem. Usually it's something like

{{data.UserName}}

that throws. This can be worked around with the safe navigation (elvis) operator

{{data?.UserName}}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • The first part mentioned is the part that is the problem. Angular2 moves on and doesn't wait for the data to come in. Is there no way to let it wait for the data before moving on? It doesn't throw btw, it just doesn't fill the variable with the needed data. – JanVanHaudt Feb 22 '16 at 07:18
  • No, this is not how it's supposed to work. This would block the UI and the user couldn't even scroll while your code waits for a response of the server. You have to cope with asynchronity in your code. If you provide more information about the actual problem I might be able to make concrete suggestions. – Günter Zöchbauer Feb 22 '16 at 07:21
  • the elvis operator solved the problem. Thank you – JanVanHaudt Feb 22 '16 at 11:18