【问题标题】:how to return my own observable depending on multiple subscribe of data如何根据数据的多次订阅返回我自己的 observable
【发布时间】:2019-04-23 21:43:41
【问题描述】:

苦苦挣扎了好几个小时.....我怎样才能返回一个自定义的 observable,它依赖于对其他 observable 的多个链式订阅。就像,我调用一个函数并订阅并检查 observable 的值,然后决定调用哪个其他函数。然后调用另一个 http 请求,从请求中获取一个新的 observable。最后,根据之前的 observable 返回我的自定义 observable。

【问题讨论】:

  • 使用 observables 时的一个好的经验法则是,您应该在消费者端只有 1 个订阅,嵌套订阅通常是一种反模式,您可以通过使用正确的运算符来解决。您还可以创建自己的主题并异步向其发出值。如果没有看到你的代码,我真的无法告诉你该怎么做

标签: angular


【解决方案1】:

https://medium.com/@danielt1263/recipes-for-combining-observables-in-rxswift-ec4f8157265f 有多种方法可以做到这一点

this.homeworld = this.http.get('/api/people/1').pipe(
 mergeMap(character => this.http.get(character.homeworld)));

这是一个可观察对象如何依赖于另一个对象的简单示例,对您的问题给出准确答案仍然是一个问题,因此您可以搜索 mergeMap。

【讨论】:

    【解决方案2】:

    使用 switchMap 操作符

    import {switchMap} from "rxjs/operators";
    import of as off from "rxjs";
          processData().pipe(switchMap(result)=>{
           if(result=="first"){
             return this.httpService.get("/api/first");
           }
           return this.httpService.get("/api/second");
        }).pipe(switchMap(response)=>{
           if(response==true){
           return off("success");  
        }
         return off("fail");
        })
    

    【讨论】:

      猜你喜欢
      • 2020-01-30
      • 1970-01-01
      • 1970-01-01
      • 2017-02-17
      • 2018-09-01
      • 2019-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多