angular-http
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinese@angular/common/http
@angular/common/http
Version: Angular 21 (2025)
Tags: HTTP, REST, API, Interceptors
版本: Angular 21(2025年)
标签: HTTP, REST, API, 拦截器
API Changes
API变更
This section documents recent version-specific API changes.
-
NEW: Functional interceptors — Usefor modern interceptor setup source
provideHttpClient(withInterceptors([...])) -
NEW:— Use native fetch API with HttpClient source
withFetch -
NEW:— Legacy interceptor support with functional approach
withInterceptorsFromDi -
NEW: HttpContext tokens — Per-request metadata using HttpContextToken
-
NEW:support — Request cancellation with timeout support
AbortSignal -
DEPRECATED: Class-based HttpInterceptor — Migrate to functional interceptors
Best Practices
最佳实践
- Use functional interceptors
ts
// ✅ Modern functional interceptor
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const authService = inject(AuthService);
const token = authService.getToken();
if (token) {
const authReq = req.clone({
setHeaders: { Authorization: `Bearer ${token}` }
});
return next(authReq);
}
return next(req);
};
// Register
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(withInterceptors([authInterceptor]))
]
};- Use interceptors for cross-cutting concerns — Authentication, logging, error handling
ts
// Error interceptor with retry
export const errorInterceptor: HttpInterceptorFn = (req, next) => {
return next(req).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 401) {
inject(Router).navigate(['/login']);
}
return throwError(() => error);
})
);
};- Use retry with backoff for flaky networks
ts
import { retry, delay, catchError } from 'rxjs/operators';
http.get('/api/data').pipe(
retry({ count: 3, delay: 1000 })
);- Use HttpContext for per-request flags
ts
const cacheToken = new HttpContextToken<boolean>(() => false);
export const cacheInterceptor: HttpInterceptorFn = (req, next) => {
if (req.context.get(cacheToken)) {
// Check cache
}
return next(req);
};
// Usage
http.get('/api/data', {
context: new HttpContext().set(cacheToken, true)
});- Use proper typing for HTTP responses
ts
interface User {
id: number;
name: string;
}
http.get<User>('/api/user/1').subscribe(user => {
console.log(user.name); // TypeScript knows the type
});- Use for full HTTP response
observe: 'response'
ts
http.get('/api/data', { observe: 'response' }).subscribe(response => {
console.log(response.headers);
console.log(response.body);
});- Handle errors globally
ts
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
handleError(error: Error) {
// Log to error tracking service
console.error(error);
}
}
// Register
provideErrorHandler(GlobalErrorHandler)- Use for CORS requests
withCredentials
ts
http.get('/api/data', { withCredentials: true });- 使用函数式拦截器
ts
// ✅ Modern functional interceptor
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const authService = inject(AuthService);
const token = authService.getToken();
if (token) {
const authReq = req.clone({
setHeaders: { Authorization: `Bearer ${token}` }
});
return next(authReq);
}
return next(req);
};
// Register
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(withInterceptors([authInterceptor]))
]
};- 将拦截器用于横切关注点 —— 身份验证、日志记录、错误处理
ts
// Error interceptor with retry
export const errorInterceptor: HttpInterceptorFn = (req, next) => {
return next(req).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 401) {
inject(Router).navigate(['/login']);
}
return throwError(() => error);
})
);
};- 针对不稳定网络使用带退避策略的重试机制
ts
import { retry, delay, catchError } from 'rxjs/operators';
http.get('/api/data').pipe(
retry({ count: 3, delay: 1000 })
);- 使用HttpContext为单个请求设置标识
ts
const cacheToken = new HttpContextToken<boolean>(() => false);
export const cacheInterceptor: HttpInterceptorFn = (req, next) => {
if (req.context.get(cacheToken)) {
// Check cache
}
return next(req);
};
// Usage
http.get('/api/data', {
context: new HttpContext().set(cacheToken, true)
});- 为HTTP响应添加合适的类型定义
ts
interface User {
id: number;
name: string;
}
http.get<User>('/api/user/1').subscribe(user => {
console.log(user.name); // TypeScript knows the type
});- 使用获取完整HTTP响应
observe: 'response'
ts
http.get('/api/data', { observe: 'response' }).subscribe(response => {
console.log(response.headers);
console.log(response.body);
});- 全局处理错误
ts
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
handleError(error: Error) {
// Log to error tracking service
console.error(error);
}
}
// Register
provideErrorHandler(GlobalErrorHandler)- CORS请求使用
withCredentials
ts
http.get('/api/data', { withCredentials: true });