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

Angular 12调用get/post方法报No provider for HttpHeaders错误如何解决

问题原因

报错No provider for HttpHeaders和两处配置遗漏有关:

  1. 你封装的EsriHttp服务没有通过构造函数注入HttpClient,仅声明了私有属性_http但未完成赋值,Angular依赖注入无法自动识别未在构造器中声明的依赖。
  2. 项目对应模块(报错提示的LayerListModule或者根模块AppModule)未导入HttpClientModule,Angular的Http相关依赖(包括HttpClient、HttpHeaders等)都需要通过这个模块注册提供者。

修复方案

1. 修正EsriHttp服务代码

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class EsriHttp {
  // 通过构造函数注入HttpClient,自动赋值给私有属性
  constructor(private _http: HttpClient) {}

  get(url: string, options?: {headers?: {[header: string]: string | string[]} }): Observable<any> {
    options = this.setOptions(options);
    return this._http.get(url, options);
  }

  post(url: string, body: any, options?: {headers?: {[header: string]: string | string[]} }): Observable<any> {
    options = this.setOptions(options);
    body = this.transformRequest(body);
    return this._http.post(url, body, options);
  }

  private setOptions(options?: {headers?: {[header: string]: string | string[]}}) {
    if (options == null) {
      options = {headers: null };
    }
    if (options.headers === null) {
        options.headers = {'Content-Type': 'application/x-www-form-urlencoded'};
    }
    return options;
  }

  private transformRequest(body) {
    if (!body.hasOwnProperty("f")) {
      body.f = "json";
    }
    let transform = (obj: any) => {
      let str = [];
      Object.keys(obj).forEach(function (key) {
        str.push(encodeURIComponent(key) + "=" + encodeURIComponent(obj[key]));
      });
      return str.join("&");
    };
    return transform(body);
  }
}

2. 修正模块配置

在LayerListModule或者根AppModule的imports数组中加入HttpClientModule:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { LayerListService } from './layer-list.service';
import { EsriHttp } from './esri-http.service';

@NgModule({
  imports: [
    BrowserModule,
    // 新增HttpClientModule导入
    HttpClientModule
  ],
  providers: [LayerListService, EsriHttp]
})
export class LayerListModule { }

补充说明

不需要单独为HttpHeaders注册提供者,只要导入HttpClientModule就会自动注册所有Http相关依赖。你现在用组合的方式封装Http请求的思路是正确的,Angular高版本中HttpClient被标记为final类,确实无法继承。

内容的提问来源于stack exchange,提问作者wondim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 18:54:03