Angular2升级至Angular12:HttpHeaders替换Headers时出现调用不匹配问题求助
Headers with HttpHeaders in Angular 12 Hey there! I totally get how frustrating these API breaking changes can be when upgrading Angular versions—let’s break down exactly what’s going wrong with your HttpHeaders implementation and fix it.
The core issue here is that HttpHeaders (from @angular/common/http) is immutable and has stricter type checking than the old Headers from @angular/http. That "No overload matches this call" error almost always stems from not adapting to these key differences. Here are the most common fixes to get you unblocked:
1. Stop modifying HttpHeaders in-place
Unlike the old Headers, every method like append(), set(), or delete() on HttpHeaders returns a new instance instead of modifying the original object. If you’re doing this:
// ❌ Broken for HttpHeaders (doesn't update the original variable) let headers = new HttpHeaders(); headers.append('Content-Type', 'application/json');
You need to reassign the result back to your variable to actually update the headers:
// ✅ Correct immutable approach let headers = new HttpHeaders(); headers = headers.append('Content-Type', 'application/json'); headers = headers.append('X-Custom-Header', 'my-value');
2. Simplify header creation with object literals
You can skip manual appends entirely by passing a plain object directly to the HttpHeaders constructor—this is cleaner and less error-prone:
// ✅ Directly initialize with header key-value pairs const headers = new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': 'Bearer my-auth-token' });
3. Fix invalid values or type mismatches
HttpHeaders enforces stricter type rules than the old Headers:
- Null/undefined values aren’t allowed—replace them with empty strings or remove the header entirely.
- For multiple values under a single header key, use an array of strings:
const headers = new HttpHeaders({ 'Accept': ['application/json', 'text/plain'] });
4. Verify your request options syntax
Double-check that you’re passing headers correctly to your HttpClient calls. The syntax is similar to the old Http, but ensure the headers property in your options matches the expected type:
// ✅ Correct HttpClient post call this.httpClient.post('/api/data', requestBody, { headers: headers }) .subscribe(response => { /* handle your response */ });
If you’re still hitting the error, sharing the exact code snippet where you’re using HttpHeaders would help narrow things down further—but these fixes resolve 90% of the "No overload matches this call" issues with header upgrades.
内容的提问来源于stack exchange,提问作者Usama Attique

