angular - Observable:如果在 map() 之前,为什么不导致 subscribe() 成功函数?

标签 angular typescript rxjs observable

我指的是这个post这对理解 Observables 非常有帮助,但还有一些我不明白的地方。

在plunker里面吧refers to ,我更改了“src/myfreinds.ts”以查看发生了什么并添加了一些控制台日志:

首先我保持原样:

  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;
        }
      );
    }
  }

在这种情况下,我可以在日志中看到 subscribe 下的 resultundefined。但是 map 下的 response 确实包含响应。

如果我去掉 map 部分并保留 subscribe 部分,如下所示:

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;
        }
      );
   }
}

这一次,在控制台中,我可以在下方看到订阅 result 的详细信息,而不是像我在之前的案例中看到的那样 undefined

我想了解为什么订阅,成功函数不包含每次是否应用 map 函数的结果?

最佳答案

subscribe() 作为 result 传递,之前的运算符 .map() 返回 - return response.json()

很有可能 response != undefined 但是 response.json() == null

关于angular - Observable:如果在 map() 之前,为什么不导致 subscribe() 成功函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40505691/

相关文章:

typescript - 如何使用 typescript 声明特定长度的字符串?

Angular 5 RxJS 订阅计时问题

javascript - 如何在 RxJS 中设定的时间间隔后对整个流进行 forEach

angular - Visual Studio/Angular - 类型参数不可分配给参数类型 ObjectIterateeCustom<any[], boolean>

angular - 为什么 Material Design 的布局不能与 Angular 4 兼容?

typescript - 联合类型的类型推断——不存在最佳通用类型

javascript - Typescript 获取函数内设置变量的名称

javascript - 使用 NGRX 存储测试异步 Angular 验证器

css - 如何使用 Bootstrap 类在 Angular 5 的同一行中对齐 div

css - 通过 Angular 路由器导航后导航不关闭