1

Can you please answer to question in comment

class TextComp 
{

result: string;
constructor() {

    this.getdata().subscribe(result => {
        console.log("result received");
        this.result = result;
    });

    console.log("called before result received " + this.result);

    //this.result is NULL/UNDEFINED because this line executed before data received

    // So how we can eliminate this situation??? or
    // Is there any way to make synchronus call to http in angular 2
}

getdata() {
    return http.get('test.json')
        .map(response => response.json());
}
}

So how we can eliminate this situation??? or Is there any way to make synchronus call to http in angular 2

ArK
  • 20,698
  • 67
  • 109
  • 136
John
  • 11
  • 1
  • 3
  • You don't want it to be synchronous, since that would make your application hang while waiting for the response. Whatever you need to do to the result, you'll have to do inside the subscribe callback. – Nikolaj Dam Larsen Jan 16 '17 at 15:20

1 Answers1

1

if you need to make synchronous calls in this case your code should be something like:

this.getdata().subscribe(result => {
    console.log("result received");
    this.result = result;
    //function or snippet which will be called after subscribe is complete...     
});

because your subscribe method works asynchronously. I recommend you also to take a look at promises.

Digao
  • 520
  • 8
  • 22