合并数据的效果如何

问题描述 投票:0回答:1

我有一个返回项目列表的服务和监听此服务的效果

    loadBanners$ = createEffect(() =>
        this.actions$.pipe(
            ofType(BannerActions.loadBanners),
            switchMap((s) =>
                this.bannersService.getAll(s.filter).pipe(
                    map((response) => BannerActions.loadBannersSuccess({ response })),
                    catchError((error) => of(BannerActions.loadBannersFail({ error })))
                )
            )
        )
    );

在响应中,我有项目代码值,我想显示来自另一个服务的项目名称

  getDictionary(codeId: string): Observable<DictionaryListResponse> {
    return this._httpClient.post<DictionaryListResponse>(this.apiUrl, { codeId: codeId});
  }

现在的问题是如何结合这两个服务并获取带有代码和名称的完整数据。

......................................

angular rxjs ngrx ngrx-effects
1个回答
0
投票

要结合这两种服务并获取包含代码和名称的完整数据,您可以使用

combineLatest()
运算符。

import { combineLatest, Observable } from 'rxjs';
import { BannerActions } from './banner.actions';
import { BannersService } from './banners.service';
import { DictionaryService } from './dictionary.service';

@Injectable()
export class BannerEffects {

  constructor(
    private actions$: Actions,
    private bannersService: BannersService,
    private dictionaryService: DictionaryService
  ) {}

  loadBanners$ = createEffect(() =>
    this.actions$.pipe(
      ofType(BannerActions.loadBanners),
      switchMap((s) =>
        combineLatest([
          this.bannersService.getAll(s.filter),
          this.dictionaryService.getDictionary('item_names'),
        ]).pipe(
          map(([banners, dictionary]) => {
            const fullData = banners.map((banner) => {
              const itemName = dictionary.find((item) => item.value === banner.itemCode)?.label;
              return {
                ...banner,
                itemName,
              };
            });
            return BannerActions.loadBannersSuccess({ response: fullData });
          }),
          catchError((error) => of(BannerActions.loadBannersFail({ error })))
        )
      )
    )
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.