如何完成 rxjs switchmap observable?

bar*_*oma 2 rxjs angular switchmap angular8 rxjs-observables

我在我的 angular 8 项目中有一个 observable,并且订阅了 ngOnInit()。

     export class ChartComponent implements OnInit {
       urlSubject: Subject<string> = new Subject();
       isLoading: BehaviorSubject<boolean> = new BehaviorSubject(false);
       chartData: BehaviorSubject<any[]> = new BehaviorSubject<any[]>([]);
       dataSubscription: Subscription;

       dataObservable: Observable<any> = this.urlSubject.pipe(
         switchMap((url: any) => this.httpClient.get<any[]>(url))
       )

       ngOnInit() {
         this.dataSubscription = this.dataObservable
          .pipe(tap(() => this.isLoading.next(true)))          
          .pipe(map((response: any) => response.result))      
          .subscribe((response: any) => this.chartData.next(response),
            () => this.isLoading.next(false),
            () => this.isLoading.next(false));

         this.urlSubject.next(this.data.settings.dataEndpoint)
      }
}
Run Code Online (Sandbox Code Playgroud)

但是复杂的方法不会触发订阅。

我正在订阅chartData那种类型是BehaviourSubject. 所以我不订阅urlSubject。因为 url 可能会随时更改 searh 或 filter 参数。

我正在使用 finilize 但它不起作用。我认为这个问题是关于 switchmap 内部孔隙的。如何完成并将加载设置为 false?

Gog*_*eli 6

您需要finalizehttpClient.get. 直到您通过调用subject.complete(). 但是 ObservablehttpClient在发出 api 响应后由完成创建,您需要使用它。

对于您的示例:

dataObservable: Observable<any> = this.urlSubject.pipe(
  tap(() => this.isLoading.next(true)),
  switchMap((url: any) =>
    this.httpClient.get<any[]>(url).pipe(
      finalize(() => this.isLoading.next(false))
    )
  )
)
Run Code Online (Sandbox Code Playgroud)