【问题标题】:Create a chain of observables and return an observable after all of them finished创建一个可观察对象链并在所有对象完成后返回一个可观察对象
【发布时间】:2020-01-09 02:41:57
【问题描述】:

我在 Angular 6 中有一个服务,其方法是“saveEntity”,可以保存执行多个请求的实体。我需要执行以下操作: 方法调用一个 url --> 一旦获得响应,我需要调用另一个 url --> 一旦获得第二个响应,我需要将最终数据返回给组件。

所以在我的组件中我会有

service.saveEntity(entity).subscribe();

进入服务,我需要做什么?

【问题讨论】:

标签: angular rxjs


【解决方案1】:
@Injectable({providedIn: 'root'})
export class MultiSaveService {

    constructor(private http: HttpClient) {
    }

    saveMultipleInParallel(): Observable<[string, number]> {
        return forkJoin([
            this.http.post<string>('my-url', {
                stringData: 'stringData'
            }),
            this.http.post<number>('my-url', {
                numberData: 1
            })
        ])
    }

    saveMultipleOneByOne(): Observable<[string, number]> {
        return this.http.post<string>('url', {stringData: 'stringData'}).pipe(
            withLatestFrom(this.http.post<number>('url', {numberData: 5}))
        )
    }
}

您的订阅应如下所示

this.multiSaveService.saveMultipleInParallel()
  .subscribe(([firstCallResult, secondCallResult]) => {
    console.log(firstCallResult);
    console.log(secondCallResult);
  })

【讨论】:

    【解决方案2】:

    service.ts

    firstOperation() {
      return http.get('url1')
    }
    
    secondOperation() {
      return http.get('url2')
    }
    

    在第一个服务之后触发第二个服务:一次可以使用mergeMap或concatMap

    bothOperations1() {
      service.firstOperation().pipe(
        mergeMap(data1 => {
         // do something with data1
         return service.secondOperation()
        })
      )
    }
    

    但是如果两个服务要并行调用,forkJoin可以使用

    bothOperations2() {
    
      return forkjoin([service.firstOperation(), service.secondOperation()])
    }
    

    component.ts

    saveEntity1() {
      service.BothOperation1().subscribe(data => {
         // do whatever is needed with the data2
      })
    }
    
    saveEntity2() {
      service.bothOperation2().subscribe(([data1, data2]) => {
         // do whatever is needed with data1 and data2
      })
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-12
      • 1970-01-01
      • 1970-01-01
      • 2019-04-23
      • 1970-01-01
      • 2019-02-18
      • 2021-12-14
      相关资源
      最近更新 更多