第二个订阅不会从 RXJS 中的第一个订阅开始从 switchMap 开始 [英] Second subscription doesn't start upon switchMap from the first one in RXJS

查看:54
本文介绍了第二个订阅不会从 RXJS 中的第一个订阅开始从 switchMap 开始的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个工作代码.它从路由器获取 ID 并将其作为参数应用以加载组件的数据.

I have this working code. It fetches the ID from the router and applies it as a parameter to get load in the data for the component.

this.route.params.subscribe(_ => {
  this.id = _.id;
  this.service.getMineral(this.id)
    .subscribe(suc => this.data = suc, err => console.log(err));
  }
);

然后,我尝试使用更好的方法,并希望在第一个订阅完成时调用第二个订阅.根据本答案中的第二个示例,我应该分享第一个结果,然后切换地图以取消订阅并继续下一个.所以我实现了以下内容.

Then, I tried to play around with better approaches and want to invoke the second subscription when the first one completes. According to the second sample in this answer, I'm supposed to share the first result and then switch map to unsubscribe from it and proceed with the next one. So I implemented the following.

const route$ = this.route.params.pipe(share());
const data$ = route$.pipe(
  switchMap(() => this.service.getMineral(this.id)));

route$.subscribe(_ => this.id = _.id);
data$.subscribe(suc => this.data = suc, err => console.log(err));

遗憾的是,这不会调用服务器,也不会将数据传递给客户端.尝试了几次修改后,由于缺乏想法,我放弃了.

Regrettably, this makes no call to the server and no data is delivered to the client. After trying several alterations, I gave up, due to lack of ideas.

这两种方法之间的显着区别是什么?我在哪里对第二个样本的解释感到困惑?

What's the significant difference between those two approaches? Where do I get confused on my interpretation of the second sample?

推荐答案

我认为你的方法很糟糕.您应该将它链接到一个 observable 中并订阅它.类似的东西

I think your approach is bad. You should chain it in one observable and subscribe to it. Something like

 this.route.params.pipe(
    switchMap(params => this.service.getMineral(params.id))).subscribe()  

这篇关于第二个订阅不会从 RXJS 中的第一个订阅开始从 switchMap 开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆