4

I refer to this post which was really helpful to understand Observables, but there is still something I don't get.

In the plunker it refers to, I changed the "src/myfreinds.ts" to see a bit what happen and added some console log:

First I left it as the same:

  export class FriendsList{

    result:Array<Object>; 
    constructor(http: Http) { 
      console.log("Friends are being called");
      http.get('friends.json')
        .map(response => {
            console.log("map");
            console.info(response);
            response.json(); //MISTAKE WAS HERE SHOULD HAVE HAD "return response.json()" INSTEAD AS EXPLAINED IN THE ANSWER GIVEN
          })
        .subscribe(result => {
          console.log("subscribe");
          console.info(result);
          this.result =result;
        }
      );
    }
  }

In that case I can see in the log that result beneath subscribe is undefined. But response beneath map contains the response indeed.

If I take away the map part and keep the subscribe part like this:

export class FriendsList{

  result:Array<Object>; 
  constructor(http: Http) { 
    console.log("Friends are being called");
    http.get('friends.json')
      .subscribe(
        result => {
          console.log("subscribe");
          console.info(result);
          this.result =result;
        }
      );
   }
}

This time, in the console I can see beneath subscribe the details of the result and not undefined like I had in previous case.

I'd like to understand why subscribe, success function does not contain everytime the result whether map function is applied or not?

sandyJoshi
  • 733
  • 9
  • 20
nyluje
  • 3,573
  • 7
  • 37
  • 67
  • "`result` beneath subscribe is `undefined`" it is not? http://plnkr.co/edit/EOkO81iMWQzeLcRiuZbr?p=preview – eko Nov 09 '16 at 11:24
  • I understand my mistake, at first, I had written `.map(response =>{console.log("map");console.info(response);response.json()})` instead of `.map(response =>{console.log("map");console.info(response);**return** response.json()})` Thanks – nyluje Nov 09 '16 at 11:32

1 Answers1

4

subscribe() gets passed as result what the previous operator .map() returns - return response.json().

It is quite possible that response != undefined but response.json() == null

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567