我在我的 angular 8 项目中有一个可观察对象,并在 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)
}
}
但是 complate 方法不会触发订阅。
我正在订阅类型为 BehaviourSubject
的 chartData
。所以我不订阅 urlSubject
。因为 url 可能会随时更改搜索或过滤器参数。
我正在使用 finilize,但它不起作用。我认为这个问题是关于 switchmap 内部孔隙的。如何完成并将加载设置为 false?
最佳答案
您需要在httpClient.get
上使用finalize
。在您通过调用 subject.complete()
手动完成之前,Subject 和 BehaviorSubject 不会完成。然而,由 httpClient
创建的 Observable 在发出 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))
)
)
)
关于angular - 如何完成 rxjs switchmap observable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61202642/