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

Angular4迁移至HttpClientService时遭遇TS2559错误求助

Fixing TS2559 Error When Migrating to Angular's HttpClient

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:

  1. Clean Up Imports
    Make sure you're only importing HttpHeaders from @angular/common/http—remove any leftover imports for the old Headers from @angular/http if 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 Observable
    
  2. Update Header Creation
    Replace any usage of new Headers(...) with new 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);
    
  3. Handling Dynamic Headers
    Keep in mind HttpHeaders is immutable—if you need to add/modify headers dynamically, reassign the result of set() or append():

    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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:54:58