Angular4迁移至HttpClientService时遭遇TS2559错误求助
Hey there, I see you're hitting that TS2559 error while switching from Angular 4's old Http service to HttpClient—let's break this down and fix it quickly.
What's Causing the Error?
The core issue is a mismatch between header types: you're trying to pass an instance of the old Headers class (from @angular/http) to HttpClient, but HttpClient only accepts either:
- An instance of
HttpHeaders(from@angular/common/http), or - A plain JavaScript object with key-value pairs for headers.
These two header classes are completely separate and incompatible, which is why TypeScript is throwing that "no properties in common" error.
How to Fix It
Let's adjust your app.service.ts code step by step:
Clean Up Imports
Make sure you're only importingHttpHeadersfrom@angular/common/http—remove any leftover imports for the oldHeadersfrom@angular/httpif they exist.import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; // Keep only this import { Observable } from 'rxjs'; // Don't forget this if you're using ObservableUpdate Header Creation
Replace any usage ofnew Headers(...)withnew HttpHeaders(...), and structure your request options correctly. Here's a clear before-and-after:❌ Old (Error-Prone) Code
// Uses the outdated Headers class—won't work with HttpClient const headers = new Headers({ 'Content-Type': 'application/json' }); return this.http.post('/api/data', payload, { headers: headers });✅ Corrected Code
// Create a valid HttpHeaders instance for HttpClient const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', // Add other headers here if needed (e.g., Authorization) 'Authorization': 'Bearer your-auth-token' }) }; return this.http.post('/api/data', payload, httpOptions);Handling Dynamic Headers
Keep in mindHttpHeadersis immutable—if you need to add/modify headers dynamically, reassign the result ofset()orappend():let headers = new HttpHeaders(); headers = headers.set('Content-Type', 'application/json'); headers = headers.append('X-Custom-Header', 'custom-value'); const httpOptions = { headers: headers };
Why This Works
HttpClient uses a streamlined request configuration system that doesn't recognize the old Headers type. By switching to HttpHeaders (or even a plain object like { 'Content-Type': 'application/json' }), you're giving HttpClient exactly the format it expects.
内容的提问来源于stack exchange,提问作者Santhosh

