【问题标题】:How Subscribe works订阅如何运作
【发布时间】:2021-12-07 13:56:10
【问题描述】:

我正在学习 rxjs 并使用 observable 和订阅。我在 component.ts 文件中有以下方法,它从 API 返回 true/false

this.http.get(apiUrl+"/actionName")
  .subscribe(result=> 
 {
 if(result){
     //step1
 //1.show success message 
  //2.call the other method 
  //3.and after returned from here
}else{// not true
 //1. show error message 
//2. returned from here
 }
});
});
 //step2
 // call another function
 }

每当我订阅一个 observable 时,它​​会立即跳转到下一行,即第 2 步,然后首先调用另一个方法。我不想这样做。

我想先运行第 1 步,直到它完全完成,然后才应该转到第 2 步。 提前谢谢你。

【问题讨论】:

  • 在回调中调用第二个方法。
  • 我试过了,但是一旦调用 get() 请求,它就不会进入 .subscribe() 内部,而是首先出现并执行 step2。
  • 查看 concatMap
  • @Indraraj26 这将允许执行 subscribe 的内部部分,而不是去这个外面。
  • no 当源更改然后内部将执行

标签: rxjs observable publish-subscribe angular11


【解决方案1】:

你没有在你的问题中这么说,但我怀疑你的

//2.call the other method

行包含一个嵌套订阅或一个承诺。如果是这种情况,那么您的同步代码当然会在您的异步代码运行之前运行。 JavaScript 是单线程环境,因此您永远不能等待其他代码运行。


相反,使用 RxJS 的各种运算符来为您管理代码的顺序。你想怎么做取决于你在做什么,但遗憾的是 call the other method 描述性不够。

假设 theOtherMethod 和 anotherFunction 实际上是奇怪命名的可观察对象,那么你可能会这样做:

this.http.get(apiUrl+"/actionName").pipe(

  switchMap(result => {
    if(result){
      return theOtherMethod;
    }
    return of("There's no result")
  }),

  switchMap(otherMethodResult => anotherFunction)

).subscribe(anotherFunctionResult => {
  /* Ignore result?*/
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 2021-05-06
    • 2012-03-14
    • 2015-08-24
    • 2020-12-20
    • 2023-03-14
    相关资源
    最近更新 更多