1

Totally new to angular 2 and having issues with capturing the results of http calls. The calls are simple and only return json with a success/fail and a message. I've started using promises for these calls and can display the results in the browser, but cannot log or alert with the results. Let me know if you need more info.

Service:

deleteTsUser(params){
    var url = this.userDeleteUrl + '?' + params.toString();

    return this.http.get(url)
      .toPromise()
      .then(this.extractData)
      .catch(this.handleError);
}

Component:

var result = this._tsUserService.deleteTsUser(params)
   .then(
     r => {
      this.result.result = r.result,
      this.result.messages = r.messages
     }
   );

console.log('RES: ' + this.result.result)

Template:

{{ result.result }} :: {{ result.messages }}

Results display properly in template, but that console.log message just logs "Res:"...why isn't this working? I'm missing something really basic, right? Thx in adv.

eko
  • 39,722
  • 10
  • 72
  • 98
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Heretic Monkey Dec 29 '16 at 18:45

1 Answers1

2

Because:

var result = this._tsUserService.deleteTsUser(params)
   .then(
     r => {
      this.result.result = r.result,
      this.result.messages = r.messages
     }
   );

is an async operation. The result will be ready inside the then callback when your deleteTsUser method is completed.

var result = this._tsUserService.deleteTsUser(params)
   .then(
     r => {
      this.result.result = r.result;
      this.result.messages = r.messages;
      console.log('RES: ' + this.result.result);
     }
   );

will log the result.

I'd recommend you to read: How do I return the response from an asynchronous call? on the async behaviour of javascript

eko
  • 39,722
  • 10
  • 72
  • 98