在继续进行主要订阅(rxJs)之前,请先在angular中等待嵌套订阅 [英] Wait for nested subscribe in angular before continuing with main subscribe (rxJs)

查看:40
本文介绍了在继续进行主要订阅(rxJs)之前,请先在angular中等待嵌套订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个问题,我需要执行所有嵌套方法(包括subscirbe),然后设置isLoading = false,但是在执行所有嵌套逻辑之前,isLoading标志设置为false.

I ran into a problematic one, I need to execute all nested methods (which include subscirbe) and only then set isLoading = false, but the isLoading flag sets to false before all the nested logic has been executed.

您能告诉我您有什么想法吗?我试图以示意性的方式编写代码,而无需赘述

Can you tell me if you have any ideas? I tried to write the code schematically without going into details

getData() {
 isLoading = true;
 this.someSevice.getSomeData().subscribe(response => {
   ...
   getUserData(response);
   isLoading = false;
 },
  error => {
    isLoading = false;
    this.errors = error;
 });
}

getUserData(data: any) {
  ...
  this.someSevice.getUserData().subscribe(response => {
    ...
    getMetadata(response);
  });
}

getMetadata(data: any) { 
  ...
  this.someSevice.getMetadata().subscribe(response => {
    ...
  });
}

推荐答案

您可以做的是使用管道通过 mergeMap 运算符顺序执行请求.如果您有顺序请求,而每个请求都需要前一个请求的响应,则这是一种常见的模式. mergeMap 至少需要一个参数,该参数必须是返回 Observable (或 Promise )的函数.因此,出于这个原因,我还修改了 getUserData getMetadata .

what you can do is using pipe to execute your requests sequentially with the mergeMap operator. This is a common pattern if you have sequential requests where each request requires the response of the prior one. mergeMap requires at least one parameter that must be a function that returns an Observable (or alternatively a Promise). So I also modified getUserData and getMetadata for that reason.

getData() {
  isLoading = true;
  this.someSevice.getSomeData().pipe(
    mergeMap(getUserData),
    mergeMap(getMetadata),
  )
  .subscribe(
    response => {
      isLoading = false;
    },
    error => {
      isLoading = false;
      this.errors = error;
    },
  );
}

getUserData(data: any) {
  ...
  return this.someSevice.getUserData();
}

getMetadata(data: any) { 
  ...
  return this.someSevice.getMetadata();
}

这篇关于在继续进行主要订阅(rxJs)之前,请先在angular中等待嵌套订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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