You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中Observable初始loading值未生效问题求助

问题:HttpWrapper服务加载状态不生效,无法显示加载动画

我试图编写一个HttpWrapper服务,将API返回结果包装成带有loading状态的对象,用于控制加载动画的显示。最初我将Observable初始化为loading: true,但并未生效——该Observable在API调用完成前似乎为null或undefined,仅在调用完成后才更新状态。

我尝试直接初始化dataObservable为带有loading: true的Observable,但同样无效:loading值始终为undefined,仅在API调用完成后变为false。

相关代码

包装器服务

import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { catchError, delay, map, Observable, of, switchMap } from 'rxjs';

export interface ApiResponse<T> {
  data: T | null;
  loading: boolean;
  error?: Error | null;
}

@Injectable({
  providedIn: 'root',
})
export class HttpWrapperService {
  #httpClient = inject(HttpClient);

  get<T>(url: string, params?: HttpParams): Observable<ApiResponse<T>> {
    return of({ data: null, loading: true, error: null }).pipe(
      delay(5000),
      switchMap(() =>
        this.#httpClient.get<T>(url, { params, withCredentials: true }).pipe(
          map(
            (data) => ({ data, loading: false, error: null } as ApiResponse<T>)
          ),
          catchError((error) =>
            of({ data: null, loading: false, error } as ApiResponse<T>)
          )
        )
      )
    );
  }
}

模板代码

<span>Loading: {{(dataObservable | async)?.loading}}</span>

组件代码

#httpWrapper = inject(HttpWrapperService);

dataObservable: Observable<ApiResponse<any>> = of({
  data: null,
  loading: true,
  error: null,
});

constructor() {
  this.dataObservable = this.#httpWrapper.get(
    'https://jsonplaceholder.typicode.com/todos/1'
  );
}

内容的提问来源于stack exchange,提问作者Raphaël VO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 12:40:01