一种解决方法是使用RxJS的takeUntil操作符,在EventSource关闭时取消订阅流。以下是一个示例:
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@Injectable()
export class MyService {
  private destroy$: Subject = new Subject();
  constructor() {}
  getData(): Observable {
    return new Observable(observer => {
      const eventSource = new EventSource('http://localhost:8080/api/data');
      eventSource.onmessage = event => {
        observer.next(event.data);
      };
      eventSource.onerror = error => {
        observer.error(error);
      };
      return () => {
        console.log('Closing EventSource...');
        eventSource.close();
      };
    }).pipe(
      takeUntil(this.destroy$)
    );
  }
  ngOnDestroy() {
    this.destroy$.next(true);
    this.destroy$.unsubscribe();
  }
}
   在上面的代码中,我们使用了一个Subject来跟踪组件或服务的销毁。我们使用takeUntil操作符来在销毁时取消订阅流。在这个例子中,我们展示了如何使用Observable来订阅EventSource对象,然后在组件或服务的ngOnDestroy方法中调用destroy$的next和unsubscribe方法来销毁这个对象。这样就可以避免Async Pipe在EventSource关闭后仍然显示加载模板的问题。