javascript - RxJs 映射后未定义的值

标签 javascript angular ecmascript-6 rxjs reactive-programming

为什么我在 subscribe 方法中未定义? 我正在尝试结合数据源。客户和类别。 我正在尝试根据类别集合中匹配的 CategoryId 来填充客户的类别属性。

STACKBLITZ

constructor(private http: HttpClient) {}
  ngOnInit() {
    const custurmersWithCategory$ = combineLatest([
      this.http
        .get<ICustomer[]>(
          "https://www.json-generator.com/api/json/get/cgqEBPcHtu?indent=4"
        )
        .pipe(delay(1000)),
      this.http.get<ICategory[]>(
        "https://www.mocky.io/v2/5db4195d300000520057b70b"
      )
    ]).pipe(
       map(([customers, categories]) => {
         customers.map(
          customer =>
            ({
              ...customer,
              Category: categories.find(
                c => customer.CategoryId === c.CategoryId
              ).category
            } as ICustomer)
        );
      })
    );

    custurmersWithCategory$.subscribe(data => {
      console.log(data);// why is this undefined?
    });
  }

最佳答案

您当前没有从 map 返回任何内容,因此您得到 undefined。正如这里所解释的:https://stackoverflow.com/a/41743119/6294072你的代码翻译成这样:

function (foo) { bar; }

它根本不返回任何内容。所以添加

return customers.map( ...

它实际上会返回一些值。

<强> STACKBLITZ

根据评论,如果不想添加return,您可以从map内部删除大括号。

<强> STACKBLITZ

作为进一步的评论,就像我链接的答案中提到的那样,这与 rxjs map 无关,而是箭头函数的工作方式:)

关于javascript - RxJs 映射后未定义的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58570237/

相关文章:

javascript - 使用 Angular $resource 执行获取请求时出错

Angular 7 - 服务 worker 未注册

javascript - 将 Angular 从 5.1 升级到 8 后 NgStyle 出现问题

javascript - 为什么我的不和谐机器人无法正常上线?

javascript - 如何将手动部署的单实例应用程序重构为客户端部署的多实例或 Multi-Tenancy 应用程序

javascript - 将Select框中选中的Option的值修改为溢出省略号

javascript - Proxy构造函数和Reflect有什么区别?

javascript - 使用 map 传播语法不起作用

javascript - snapshot.docChanges() 在 Firebase Firestore 中不起作用

javascript - 如何将本地文件读入字符串