使用RxJS Observables进行单次成功回调

时间:2018-05-22 10:37:13

标签: javascript angular typescript rxjs

如何在允许每个observable拥有自己的成功/错误块的情况下,使用observable进行单次成功回调?我有一个动态的AJAX调用列表,需要进行调用,并且每个调用都需要它在回调方法上。在每次AJAX调用完成后,我也希望有一个回调方法。我尝试使用zip,但AJAX调用被调用两次。

示例:

var possibleRequest1 = Observable.create(() => {}).subscribe(_ => {
    //Must have a success callback
});
var possibleRequest2 = Observable.create(() => {}).subscribe(_ => {
    //Must have a success callback
});
var possibleRequest3 = Observable.create(() => {}).subscribe(_ => {
    //Must have a success callback
});

//User 1 might need to make requests 1 and 2
var dynamicRequstList = [possibleRequest1, possibleRequest2];
//User 2 might need to make all three requests
var dynamicRequstList = [possibleRequest1, possibleRequest2, possibleRequest3];

zip(...dynamicRequestList)
.subscribe(() => {
    //Need a callback after all requests are complete.
});

1 个答案:

答案 0 :(得分:2)

您可以使用rxjs中的forkJoinHere示例如何在您的问题示例中使用forkJoin。

<强> service.ts

constructor(private http: HttpClient) { }

requestList1$ = new Subject();
requestList2$ = new Subject();

getDynamicRequstList1() {
    forkJoin(
      this.getItems1(),
      this.getItems2()
    ).subscribe(res => this.requestList1$.next(res));
}

getDynamicRequstList2() {
    forkJoin(
      this.getItems1(),
      this.getItems2(),
      this.getItems3()
    ).subscribe(res => this.requestList2$.next(res));
}  

getItems1(): Observable<any> {
    return of({
      item1: 'Item 1'
    });
}  

getItems2(): Observable<any> {
    return of({
      item1: 'Item 2'
    });
  }  

getItems3(): Observable<any> {
    return of({
      item1: 'Item 3'
    });
}

<强> component.ts

constructor(private service: AppService) { }

ngOnInit() {
  this.service.requestList1$.subscribe(res => console.log('RES 1:::', res))
  this.service.requestList2$.subscribe(res => console.log('RES 2:::', res))
}