0

我正在尝试检查我在 Typescript 中编写的与 RxJS observables 一致的函数的有效性,该函数从一项服务中获取一些预订,然后为每个预订从另一项服务中获取其相应的位置和活动。

我写这篇文章只是为了验证我所写内容的有效性,并询问是否有什么我可以做的更有效。

let params = new HttpParams();
params = params.append('status', 'C');
params = params.append('offset', offset.toString());
params = params.append('limit', limit.toString());
return this.http.get(`${this.environment.booking.url}/my/bookings`, { params }).pipe(
    mergeMap((bookings: Booking[]) => {
        if(bookings.length > 0) {
            return forkJoin(
                bookings.map((booking: Booking) =>
                    forkJoin(
                        of(booking),
                        this.activityService.getActivity(booking.activity),
                  this.locationService.getLocation(booking.finalLocation),
                    ).pipe(
                        map((data: [ Booking, Activity, Location ]) => {
                            let booking = data[0];
                            booking.activityData = data[1];
                            booking.finalLocationData = data[2];
                            return booking;
                        })
                    )
                )
            )
        }

        return of([]);
    }),
    catchError((err: HttpErrorResponse) => throwError(err))
);

我期待这个函数返回一个预订列表以及相应的位置和活动。但更重要的是,我想验证我所做的是否正确和明智。有什么我可以做的不同的事情来使它更清晰/更易于阅读(请不要吹毛求疵)?

另一方面,关于性能,我还有一个关于性能的后续问题。鉴于预订列表具有共同的活动和位置。有没有办法只获取活动和位置而没有任何重复的 HTTP 请求?这是否已经由 RxJS 在后台处理了?我可以做些什么来提高这个功能的效率吗?

4

2 回答 2

0

I'm not sure about the efficiency, but, at least for me, it was a little hard to read

Here's how I'd do it:

I used a dummy API, but I think it correlates with your situation

const usersUrl = 'https://jsonplaceholder.typicode.com/users';
const todosUrl = 'https://jsonplaceholder.typicode.com/todos';
const userIds$ = of([1, 2, 3]); // Bookings' equivalent

userIds$
  .pipe(
    filter(ids => ids.length !== 0),
    // Flatten the array so we can avoid another nesting level
    mergeMap(ids => from(ids)),
    // `concatMap` - the order matters!
    concatMap(
      id => forkJoin(ajax(`${usersUrl}/${id}`), ajax(`${todosUrl}/${id}`))
        .pipe(
          map(([user, todo]) => ({ id, user: user.response, todo: todo.response }))
        )
    ),
   toArray()
  )
  .subscribe(console.log)

Here is a StackBlitz demo.

With this in mind, here is how I'd adapt it to your problem:

this.http.get(`${this.environment.booking.url}/my/bookings`, { params }).pipe(
    filter(bookings => bookings.length !== 0),
    // Get each booking individually
    mergeMap(bookings => from(bookings)),
    concatMap(
        b => forkJoin(
            this.activityService.getActivity(b.activity),
            this.locationService.getLocation(b.finalLocation),
        )
        .pipe(
            map(([activity, location]) => ({ ...b, activity, location }))
        )
    ),
    // Getting the bookings array again
    toArray()
    catchError((err: HttpErrorResponse) => throwError(err))
);
于 2019-11-02T15:26:32.257 回答
0

这就是我使用 RxJS 解决这个问题的方法:

  1. 获取所有Bookings
  2. 对于每个 Booking 获取LocationActivities并发

const { from, of, forkJoin, identity } = rxjs;
const { mergeMap, tap, catchError } = rxjs.operators;

const api = 'https://jsonplaceholder.typicode.com';

const endpoints = {
  bookings: () => `${api}/posts`,
  locations: (id) => `${api}/posts/${id}/comments`,
  activities: (id) => `${api}/users/${id}`
};

const fetch$ = link => from(fetch(link)).pipe(
  mergeMap(res => res.json()),
  catchError(() => from([])),
);

fetch$(endpoints.bookings()).pipe(
  mergeMap(identity),
  mergeMap(booking => forkJoin({
    booking: of(booking),
    locations: fetch$(endpoints.locations(booking.id)),
    activities: fetch$(endpoints.activities(booking.userId)),
  })),
).subscribe(console.log);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.3/rxjs.umd.js" integrity="sha256-Nihli32xEO2dsnrW29M+krVxoeDblkRBTkk5ZLQJ6O8=" crossorigin="anonymous"></script>


注意

  1. 反应式编程和更一般的声明性方法,专注于避免命令式控制流......您应该尝试编写没有条件(或任何其他控制流)的管道。要丢弃空预订,您可以使用filter运营商。
  2. 避免嵌套流,因为这是以可读性为代价的。
  3. forkJoin还需要一个非常有用的规范对象(部分重载)
于 2019-11-02T15:10:25.743 回答