Angular:ForkJoin ngrx observables

时间:2018-04-17 17:27:01

标签: angular rxjs observable

我有一个包含多个状态的ngrx商店。我试图通过从每个状态收集数据来构造一个对象(Rent对象): 这是我的代码:

ngOnInit() {


  //Fetch the rent and its properties data
  const rentID = +this.route.snapshot.params['id'];

  let rentState$ = this.store.select('rentState');
  let clientState$ = this.store.select('clientState');
  let vehiculeState$ = this.store.select('vehiculesState');
  let paymentState$ = of(null);//TODO

  let importRent$ = forkJoin([rentState$, vehiculeState$, clientState$, paymentState$])
    .pipe(mergeMap(([rentData, vehiculeData, clientData, paymentData]: [any, any, any, any]) => {
      let rent = new Rent();

      rent = rentData.rentList.filter(rent => rent.id === rentID)[0];

      rent.vehicule = vehiculeData.vehicules.filter(vehicule => vehicule.id === this.rent.vehicule.id)[0];

      rent.client = clientData.clientList.filter(client => client.id === this.rent.client.id)[0];
      rent.companion = clientData.companionList.filter(companion => companion.id === this.rent.companion.id)[0];

      //TODO: retrieve payments

      return of(rent);
    }))


  importRent$.subscribe(data => console.log('hello'));

}

但我没有收到任何消息“你好”。在我的控制台中。由于某种原因,订阅不会发生。

我的代码中已经有这些导入:

import { Observable } from 'rxjs/Observable';
import { forkJoin } from 'rxjs/observable/forkJoin';
import { of } from 'rxjs/observable/of';
import { mergeMap } from 'rxjs/operators';

商店里面已有数据。知道我做错了什么吗?

2 个答案:

答案 0 :(得分:3)

您是否肯定所有州都会排放并完成?试试combineLatest?而且我认为您不需要将可观察数据放在数组中作为forkJoin的参数。

使用combineLatest时,每次child-source Observable在所有child-source的初始发射后发出,整个事件都会发出。如果您不想要distinctUntilChanged方案,您可能也想查看over-emitting

1 emits, 2 emits => combineLatest emits => 1 emits => combineLatest emits等......

答案 1 :(得分:1)

@martin在评论中说

  

forkJoin要求完成所有源可观察对象。

因此,您只需要获取take(1)first()发出的第一个值:

let importRent$ = combineLatest(
  rentState$.pipe(take(1)), 
  vehiculeState$.pipe(take(1)), 
  clientState$.pipe(take(1)), 
  paymentState$.pipe(take(1))
)