Observable: Why result not in subscribe() success function if preceded by map()?

梦想与她 提交于 2020-01-03 16:50:59

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/40505691/observable-why-result-not-in-subscribe-success-function-if-preceded-by-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!