deepseek 给出了正确的回答:
For a spinner/loading state, BehaviorSubject<boolean> is generally the better choice because of its stateful nature and immediate value access. Here's why and how to use it:
Why BehaviorSubject<boolean>?
- Initial State
A spinner typically starts as false (hidden), and BehaviorSubject enforces this initial state.- Synchronous Access
Components can read the current state instantly with getValue() (e.g., for conditional checks).- State Retention
New subscribers (e.g., components mounting later) will immediately know if the spinner is already active.- Manual Control
You can explicitly show/hide the spinner with next(true)/next(false) from anywhere (HTTP interceptors, services, components).
deepseek 也给出了有用的示例代码
// spinner.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class SpinnerService {
private isLoading = new BehaviorSubject<boolean>(false);
isLoading$ = this.isLoading.asObservable(); // Expose as Observable for safety
show() {
this.isLoading.next(true);
}
hide() {
this.isLoading.next(false);
}
}
<!-- spinner.component.html -->
<div *ngIf="spinnerService.isLoading$ | async" class="spinner">
Loading...
</div>