angular-http

angular-http

热门

使用 Angular v20+ 中的 resource()、httpResource() 和 HttpClient 实现 HTTP 数据获取。适用于 API 调用、基于信号的 data loading、请求/响应处理以及拦截器。触发场景包括数据获取、API 集成、加载状态、错误处理,或将基于 Observable 的 HTTP 模式转换为基于信号的模式。

596Star
70Fork
更新于 2026/3/23
SKILL.md
readonly只读
name
angular-http
description

使用 Angular v20+ 中的 resource()、httpResource() 和 HttpClient 实现 HTTP 数据获取。适用于 API 调用、基于信号的 data loading、请求/响应处理以及拦截器。触发场景包括数据获取、API 集成、加载状态、错误处理,或将基于 Observable 的 HTTP 模式转换为基于信号的模式。

Angular HTTP 与数据获取

在 Angular 中使用基于信号的 resource()httpResource() 以及传统的 HttpClient 获取数据。

httpResource() - 基于信号的 HTTP

httpResource() 将 HttpClient 封装为基于信号的状态管理:

import { Component, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';

interface User {
  id: number;
  name: string;
  email: string;
}

@Component({
  selector: 'app-user-profile',
  template: `
    @if (userResource.isLoading()) {
      <p>加载中...</p>
    } @else if (userResource.error()) {
      <p>错误:{{ userResource.error()?.message }}</p>
      <button (click)="userResource.reload()">重试</button>
    } @else if (userResource.hasValue()) {
      <h1>{{ userResource.value().name }}</h1>
      <p>{{ userResource.value().email }}</p>
    }
  `,
})
export class UserProfile {
  userId = signal('123');
  
  // 响应式 HTTP 资源 - 当 userId 变化时重新获取
  userResource = httpResource<User>(() => `/api/users/${this.userId()}`);
}

httpResource 选项

// 简单的 GET 请求
userResource = httpResource<User>(() => `/api/users/${this.userId()}`);

// 带完整请求选项
userResource = httpResource<User>(() => ({
  url: `/api/users/${this.userId()}`,
  method: 'GET',
  headers: { 'Authorization': `Bearer ${this.token()}` },
  params: { include: 'profile' },
}));

// 带默认值
usersResource = httpResource<User[]>(() => '/api/users', {
  defaultValue: [],
});

// 当参数未定义时跳过请求
userResource = httpResource<User>(() => {
  const id = this.userId();
  return id ? `/api/users/${id}` : undefined;
});

资源状态

// 状态信号
userResource.value()      // 当前值或 undefined
userResource.hasValue()   // 布尔值 - 是否有已解析的值
userResource.error()      // 错误或 undefined
userResource.isLoading()  // 布尔值 - 是否正在加载
userResource.status()     // 'idle' | 'loading' | 'reloading' | 'resolved' | 'error' | 'local'

// 操作
userResource.reload()     // 手动触发重新加载
userResource.set(value)   // 设置本地值
userResource.update(fn)   // 更新本地值

resource() - 通用异步数据

用于非 HTTP 异步操作或自定义获取逻辑:

import { resource, signal } from '@angular/core';

@Component({...})
export class Search {
  query = signal('');
  
  searchResource = resource({
    // 响应式参数 - 变化时触发重新加载
    params: () => ({ q: this.query() }),
    
    // 异步加载器函数
    loader: async ({ params, abortSignal }) => {
      if (!params.q) return [];
      
      const response = await fetch(`/api/search?q=${params.q}`, {
        signal: abortSignal,
      });
      return response.json() as Promise<SearchResult[]>;
    },
  });
}

带默认值的资源

todosResource = resource({
  defaultValue: [] as Todo[],
  params: () => ({ filter: this.filter() }),
  loader: async ({ params }) => {
    const res = await fetch(`/api/todos?filter=${params.filter}`);
    return res.json();
  },
});

// value() 返回 Todo[](永远不会是 undefined)

条件加载

const userId = signal<string | null>(null);

userResource = resource({
  params: () => {
    const id = userId();
    // 返回 undefined 以跳过加载
    return id ? { id } : undefined;
  },
  loader: async ({ params }) => {
    return fetch(`/api/users/${params.id}`).then(r => r.json());
  },
});
// 当 params 返回 undefined 时,状态为 'idle'

HttpClient - 传统方式

适用于复杂场景或需要使用 Observable 操作符时:

import { Component, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { toSignal } from '@angular/core/rxjs-interop';

@Component({...})
export class Users {
  private http = inject(HttpClient);
  
  // 将 Observable 转换为 Signal
  users = toSignal(
    this.http.get<User[]>('/api/users'),
    { initialValue: [] }
  );
  
  // 或直接使用 Observable
  users$ = this.http.get<User[]>('/api/users');
}

HTTP 方法

private http = inject(HttpClient);

// GET
getUser(id: string) {
  return this.http.get<User>(`/api/users/${id}`);
}

// POST
createUser(user: CreateUserDto) {
  return this.http.post<User>('/api/users', user);
}

// PUT
updateUser(id: string, user: UpdateUserDto) {
  return this.http.put<User>(`/api/users/${id}`, user);
}

// PATCH
patchUser(id: string, changes: Partial<User>) {
  return this.http.patch<User>(`/api/users/${id}`, changes);
}

// DELETE
deleteUser(id: string) {
  return this.http.delete<void>(`/api/users/${id}`);
}

请求选项

this.http.get<User[]>('/api/users', {
  headers: {
    'Authorization': 'Bearer token',
    'Content-Type': 'application/json',
  },
  params: {
    page: '1',
    limit: '10',
    sort: 'name',
  },
  observe: 'response', // 获取完整的 HttpResponse
  responseType: 'json',
});

拦截器

函数式拦截器(推荐)

// auth.interceptor.ts
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const authService = inject(Auth);
  const token = authService.token();
  
  if (token) {
    req = req.clone({
      setHeaders: { Authorization: `Bearer ${token}` },
    });
  }
  
  return next(req);
};

// error.interceptor.ts
export const errorInterceptor: HttpInterceptorFn = (req, next) => {
  return next(req).pipe(
    catchError((error: HttpErrorResponse) => {
      if (error.status === 401) {
        inject(Router).navigate(['/login']);
      }
      return throwError(() => error);
    })
  );
};

// logging.interceptor.ts
export const loggingInterceptor: HttpInterceptorFn = (req, next) => {
  const started = Date.now();
  return next(req).pipe(
    tap({
      next: () => console.log(`${req.method} ${req.url} - ${Date.now() - started}ms`),
      error: (err) => console.error(`${req.method} ${req.url} failed`, err),
    })
  );
};

注册拦截器

// app.config.ts
import { provideHttpClient, withInterceptors } from '@angular/common/http';

export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(
      withInterceptors([
        authInterceptor,
        errorInterceptor,
        loggingInterceptor,
      ])
    ),
  ],
};

错误处理

使用 httpResource

@Component({
  template: `
    @if (userResource.error(); as error) {
      <div class="error">
        <p>{{ getErrorMessage(error) }}</p>
        <button (click)="userResource.reload()">重试</button>
      </div>
    }
  `,
})
export class UserCmpt {
  userResource = httpResource<User>(() => `/api/users/${this.userId()}`);
  
  getErrorMessage(error: unknown): string {
    if (error instanceof HttpErrorResponse) {
      return error.error?.message || `Error ${error.status}: ${error.statusText}`;
    }
    return '发生意外错误';
  }
}

使用 HttpClient

import { catchError, retry } from 'rxjs';

getUser(id: string) {
  return this.http.get<User>(`/api/users/${id}`).pipe(
    retry(2), // 最多重试 2 次
    catchError((error: HttpErrorResponse) => {
      console.error('获取用户时出错:', error);
      return throwError(() => new Error('加载用户失败'));
    })
  );
}

加载状态模式

@Component({
  template: `
    @switch (dataResource.status()) {
      @case ('idle') {
        <p>输入搜索词</p>
      }
      @case ('loading') {
        <app-spinner />
      }
      @case ('reloading') {
        <app-data [data]="dataResource.value()" />
        <app-spinner size="small" />
      }
      @case ('resolved') {
        <app-data [data]="dataResource.value()" />
      }
      @case ('error') {
        <app-error 
          [error]="dataResource.error()" 
          (retry)="dataResource.reload()" 
        />
      }
    }
  `,
})
export class Data {
  query = signal('');
  dataResource = httpResource<Data[]>(() => 
    this.query() ? `/api/search?q=${this.query()}` : undefined
  );
}

有关高级模式,请参阅 references/http-patterns.md