首页 新闻 会员 周边 捐助

angular: 在 spinner 场景是使用 BehaviorSubject<boolean> 还是 Observable<boolean>

0
悬赏园豆:30 [已解决问题] 解决于 2025-04-04 22:35

如题,在 spinner 场景表示是否正在加载或者操作的变量类型是使用 BehaviorSubject<boolean> 还是 Observable<boolean>

dudu的主页 dudu | 高人七级 | 园豆:24728
提问于:2025-04-04 19:39
< >
分享
最佳答案
0

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>
dudu | 高人七级 |园豆:24728 | 2025-04-04 20:00
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册