使用RxJS的flatMap操作符来将嵌套的订阅操作转换为链式操作。
示例代码:
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { fromEvent } from 'rxjs';
import { map, flatMap } from 'rxjs/operators';
@Component({
  selector: 'app-my-component',
  template: `
    Some content
  `,
})
export class MyComponent implements OnInit {
  @ViewChild('myDiv') myDiv: ElementRef;
  ngOnInit(): void {
    const divIntersection$ = fromEvent(this.myDiv.nativeElement, 'intersection').pipe(
      map((event: IntersectionObserverEntry) => event.isIntersecting)
    );
    const viewportIntersection$ = fromEvent(window, 'intersection').pipe(
      map((event: IntersectionObserverEntry) => event.isIntersecting)
    );
    divIntersection$
      .pipe(
        flatMap((divIsIntersecting) => {
          if (divIsIntersecting) {
            return viewportIntersection$;
          } else {
            return [];
          }
        })
      )
      .subscribe((viewportIsIntersecting) => {
        // Do something with viewportIsIntersecting
      });
  }
}