1

TYPESCRIPT CODE:

helloworld(){
    this.get_data().then(data => {
      console.log(data);
    });
}

get_data(){
    return this.http.get('assets/data/user.json').map(res => res.json()).subscribe(data => {
        return this.json_data = data;
    });
}

Anyone can please tell me why then is not working. How can I resolve this? Sorry for my weak English.

Community
  • 1
  • 1
  • You are doing .then on .sbscribe, that's why. Check out this: https://stackoverflow.com/q/34671715/5468463 – Vega Mar 17 '18 at 13:06
  • 1
    Possible duplicate of [Angular2 http.get() ,map(), subscribe() and observable pattern - basic understanding](https://stackoverflow.com/questions/34671715/angular2-http-get-map-subscribe-and-observable-pattern-basic-understan) – georgeawg Mar 17 '18 at 15:37

1 Answers1

2

You can't do then on a subscribe. You have an observable which generates a stream of data, this means that you can't actually know when the stream will end.

In the other hand then is used with promises. A promise has only ONE data to return. Once the data arrive the then activates.

In your case this what you need to do:

helloworld(){
    this.get_data().subscribe(data => {
        console.log(data);
    })
}

get_data(){
    return this.http.get('assets/data/user.json').map(res => res.json());
}
Melchia
  • 22,578
  • 22
  • 103
  • 117