从 Observable 中获取 N 个值,直到它基于一个事件完成。延迟加载多 select 列表

Take N values from Observable until its complete based on an event. Lazy loading a multi select list

我是 rxjs 的新手,我正在开发一个 angular 多选列表组件,它应该呈现一长串值 (500+)。 我正在根据 UL 渲染列表,我正在迭代将渲染 LI 的可观察对象。 我正在考虑我的选择,以避免通过一次渲染所有元素来影响性能。但我不知道这是否可能,如果可能的话,最好使用什么运算符。

建议的解决方案:

在下面找到我的代码,我仍然需要实施建议的解决方案,但我卡在了这一点上。

编辑:我正在实施@martin 解决方案,但我仍然无法在我的代码中使用它。我的第一步是在代码中复制它,以获取记录的值,但是可观察对象立即完成而没有产生任何值。 我没有触发事件,而是添加了一个主题。每次 scrollindEnd 输出发出时,我都会向主题推送一个新值。已修改模板以支持此功能。

multiselect.component.ts

import { Component, AfterViewInit } from '@angular/core';
import { zip, Observable, fromEvent, range } from 'rxjs';
import { map, bufferCount, startWith, scan } from 'rxjs/operators';
import { MultiSelectService, ProductCategory } from './multiselect.service';

@Component({
  selector: 'multiselect',
  templateUrl: './multiselect.component.html',
  styleUrls: ['./multiselect.component.scss']
})
export class MultiselectComponent implements AfterViewInit {

  SLICE_SIZE = 100;
  loadMore$: Observable<Event>;
  numbers$ = range(450);

  constructor() {}


  ngAfterViewInit() {
    this.loadMore$ = fromEvent(document.getElementsByTagName('button')[0], 'click');

    zip(
      this.numbers$.pipe(bufferCount(this.SLICE_SIZE)),
      this.loadMore$.pipe(),
    ).pipe(
      map(results => console.log(results)),
    ).subscribe({
      next: v => console.log(v),
      complete: () => console.log('complete ...'),
    });
  }

}

multiselect.component.html

<form action="#" class="multiselect-form">
  <h3>Categories</h3>
  <input type="text" placeholder="Search..." class="multiselect-form--search" tabindex="0"/>
  <multiselect-list [categories]="categories$ | async" (scrollingFinished)="lazySubject.next($event)">
  </multiselect-list>
  <button class="btn-primary--large">Proceed</button>
</form>

多选-list.component.ts

import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'multiselect-list',
  templateUrl: './multiselect-list.component.html'
})
export class MultiselectListComponent {
  @Output() scrollingFinished = new EventEmitter<any>();
  @Input() categories: Array<string> = [];

  constructor() {}

  onScrollingFinished() {
    this.scrollingFinished.emit(null);
  }
}

多选-list.component.html

<ul class="multiselect-list" (scrollingFinished)="onScrollingFinished($event)">
  <li *ngFor="let category of categories; let idx=index" scrollTracker class="multiselect-list--option">
    <input type="checkbox" id="{{ category }}" tabindex="{{ idx + 1 }}"/>
    <label for="{{ category }}">{{ category }}</label>
  </li>
</ul>

注意: scrollingFinished 事件由保存跟踪逻辑的 scrollTracker 指令触发。我正在将事件从多选列表冒泡到多选组件。

提前致谢!

这是一个live demo on Stackblitz.

如果您的组件订阅了一个包含要显示的整个列表的可观察对象,则您的服务将必须包含整个列表并在每次添加项目时发送一个新列表。这是使用此模式的实现。由于列表是通过引用传递的,每个推送到 observable 中的列表只是一个引用而不是列表的副本,因此发送一个新列表不是一个昂贵的操作。

对于服务,使用 BehaviorSubject 将您的新项目注入到您的可观察对象中。您可以使用其 asObservable() 方法从中获取一个可观察对象。使用另一个 属性 来保存您当前的列表。每次调用 loadMore() 时,将新项目推送到您的列表中,然后将此列表推送到主题中,这也会将其推送到可观察对象中,您的组件将重新呈现。

这里我从一个包含所有项目 (allCategories) 的列表开始,每次调用 loadMore() 时,如果使用 [=19] 将一个 100 项目块放在当前列表中=]:

@Injectable({
  providedIn: 'root'
})
export class MultiSelectService {
  private categoriesSubject = new BehaviorSubject<Array<string>>([]);
  categories$ = this.categoriesSubject.asObservable();
  categories: Array<string> = [];
  allCategories: Array<string> = Array.from({ length: 1000 }, (_, i) => `item #${i}`);

  constructor() {
    this.getNextItems();
    this.categoriesSubject.next(this.categories);
  }

  loadMore(): void {
    if (this.getNextItems()) {
      this.categoriesSubject.next(this.categories);
    }
  }

  getNextItems(): boolean {
    if (this.categories.length >= this.allCategories.length) {
      return false;
    }
    const remainingLength = Math.min(100, this.allCategories.length - this.categories.length);
    this.categories.push(...this.allCategories.slice(this.categories.length, this.categories.length + remainingLength));
    return true;
  }
}

然后在到达底部时从 multiselect 组件调用服务上的 loadMore() 方法:

export class MultiselectComponent {
  categories$: Observable<Array<string>>;

  constructor(private dataService: MultiSelectService) {
    this.categories$ = dataService.categories$;
  }

  onScrollingFinished() {
    console.log('load more');
    this.dataService.loadMore();
  }
}

在您的 multiselect-list 组件中,将 scrollTracker 指令放在包含 ul 而不是 li 上:

<ul class="multiselect-list" scrollTracker (scrollingFinished)="onScrollingFinished()">
  <li *ngFor="let category of categories; let idx=index"  class="multiselect-list--option">
    <input type="checkbox" id="{{ category }}" tabindex="{{ idx + 1 }}"/>
    <label for="{{ category }}">{{ category }}</label>
  </li>
</ul>

为了检测滚动到底部并仅触发一次事件,请使用此逻辑来实现您的 scrollTracker 指令:

@Directive({
  selector: '[scrollTracker]'
})
export class ScrollTrackerDirective {
  @Output() scrollingFinished = new EventEmitter<void>();

  emitted = false;

  @HostListener("window:scroll", [])
  onScroll(): void {
    if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight && !this.emitted) {
      this.emitted = true;
      this.scrollingFinished.emit();
    } else if ((window.innerHeight + window.scrollY) < document.body.offsetHeight) {
      this.emitted = false;
    }
  }
}

希望对您有所帮助!

此示例生成一个包含 450 个项目的数组,然后将它们拆分为 100 的块。它首先转储前 100 个项目,在每次单击按钮后,它会获取另一个 100 并将其附加到之前的结果中。此链在加载所有数据后正确完成。

我认为您应该能够接受并使用它来解决您的问题。只需使用 Subject 代替按钮点击,每次用户滚动到底部时都会发出:

import { fromEvent, range, zip } from 'rxjs'; 
import { map, bufferCount, startWith, scan } from 'rxjs/operators';

const SLICE_SIZE = 100;

const loadMore$ = fromEvent(document.getElementsByTagName('button')[0], 'click');
const data$ = range(450);

zip(
  data$.pipe(bufferCount(SLICE_SIZE)),
  loadMore$.pipe(startWith(0)),
).pipe(
  map(results => results[0]),
  scan((acc, chunk) => [...acc, ...chunk], []),
).subscribe({
  next: v => console.log(v),
  complete: () => console.log('complete'),
});

现场演示:https://stackblitz.com/edit/rxjs-au9pt7?file=index.ts

如果您担心性能,您应该对 *ngFor 使用 trackBy 以避免重新渲染现有的 DOM 元素,但我想您已经知道了。