【问题标题】:No provider for HttpClient没有 HttpClient 的提供者
【发布时间】:2018-04-24 12:28:39
【问题描述】:

从 Angular 4.4 升级到 5.0 并将所有 HttpModule 和 Http 更新为 HttpClientModule 后,我开始收到此错误。

我还再次添加了 HttpModule 以确保它不是由于某些依赖关系,但它不能解决问题

在 app.module 中,我都正确设置了

import { HttpModule } from '@angular/http';
import { HttpClientModule, HttpClient } from '@angular/common/http';
.
.
.
@NgModule({
    imports: [
        BrowserModule,
        HttpClientModule,
        HttpModule,
        BrowserAnimationsModule,
        FormsModule,
        AppRoutingModule,
.
.
.

我不知道这个错误是从哪里来的,或者我不知道如何理解它。我也有一个警告(也放在下面)可能是相关的。

Error: StaticInjectorError[HttpClient]: 
  StaticInjectorError[HttpClient]: 
    NullInjectorError: No provider for HttpClient!
    at _NullInjector.get (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:5665)
    at resolveToken (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:5953)
    at tryResolveToken (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:5895)
    at StaticInjector.get (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:5766)
    at resolveToken (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:5953)
    at tryResolveToken (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:5895)
    at StaticInjector.get (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:5766)
    at resolveNgModuleDep (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:15328)
    at _createClass (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:15373)
    at _createProviderInstance$1 (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:15339)

警告信息:

./node_modules/@angular/Common/esm5/http.js
There are multiple modules with names that only differ in casing.
This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
Use equal casing. Compare these module identifiers:
* D:\XXX\node_modules\@angular\Common\esm5\http.js
    Used by 21 module(s), i. e.
    D:\XXX\node_modules\awesome-typescript-loader\dist\entry.js?silent=true!D:\XXX\node_modules\angular2-template-loader\index.js!D:\XXX\ClientApp\app\services\notification-endpoint.service.ts
* D:\XXX\node_modules\@angular\common\esm5\http.js
    Used by 1 module(s), i. e.
    D:\XXX\node_modules\awesome-typescript-loader\dist\entry.js?silent=true!D:\XXX\node_modules\angular2-template-loader\index.js!D:\XXX\ClientApp\app\app.module.ts
 @ ./node_modules/@angular/Common/esm5/http.js
 @ ./ClientApp/app/services/notification-endpoint.service.ts
 @ ./ClientApp/app/app.module.ts
 @ ./ClientApp/boot.browser.ts
 @ multi event-source-polyfill webpack-hot-middleware/client?path=__webpack_hmr&dynamicPublicPath=true ./ClientApp/boot.browser.ts

当前行为

StaticInjectorError[HttpClient]: StaticInjectorError[HttpClient]: NullInjectorError: No provider for HttpClient!

环境

Angular version: 5.0.0 and 5.0.1 (also 5.1 beta)

Browser:
- all

For Tooling issues:
- Node version: 8.5.0
- Platform:  windows
{
  "name": "X",
  "version": "1.0.0",
  "description": "X",
  "author": {
    "name": "X X",
    "email": "XX",
    "url": "X"
  },
  "homepage": "X",
  "dependencies": {
    "@angular/animations": "^5.1.0-beta.0",
    "@angular/common": "^5.1.0-beta.0",
    "@angular/compiler": "^5.1.0-beta.0",
    "@angular/compiler-cli": "^5.1.0-beta.0",
    "@angular/core": "^5.1.0-beta.0",
    "@angular/forms": "^5.1.0-beta.0",
    "@angular/http": "^5.1.0-beta.0",
    "@angular/platform-browser": "^5.1.0-beta.0",
    "@angular/platform-browser-dynamic": "^5.1.0-beta.0",
    "@angular/platform-server": "^5.1.0-beta.0",
    "@angular/router": "^5.1.0-beta.0",
    "@ngtools/webpack": "^1.8.0",
    "@ngx-translate/core": "^8.0.0",
    "@ngx-translate/http-loader": "^2.0.0",
    "@swimlane/ngx-datatable": "^11.0.3",
    "@types/jquery": "^3.2.16",
    "@types/webpack-env": "^1.13.2",
    "angular2-template-loader": "^0.6.2",
    "aspnet-webpack": "^2.0.1",
    "awesome-typescript-loader": "^3.3.0",
    "bootstrap": "^3.3.7",
    "bootstrap-datepicker": "^1.7.1",
    "bootstrap-select": "^1.12.4",
    "bootstrap-toggle": "^2.2.2",
    "bootstrap-vertical-tabs": "^1.2.2",
    "chart.js": "^2.7.1",
    "core-js": "^2.5.1",
    "css": "^2.2.1",
    "css-loader": "^0.28.7",
    "event-source-polyfill": "^0.0.11",
    "expose-loader": "^0.7.3",
    "extract-text-webpack-plugin": "^3.0.2",
    "file-loader": "^1.1.5",
    "font-awesome": "^4.7.0",
    "html-loader": "^0.5.1",
    "jquery": "^3.2.1",
    "json-loader": "^0.5.7",
    "ng2-charts": "^1.6.0",
    "ng2-toasty": "^4.0.3",
    "ngx-bootstrap": "^2.0.0-beta.8",
    "node-sass": "^4.6.0",
    "popper.js": "^1.12.6",
    "raw-loader": "^0.5.1",
    "rxjs": "^5.5.2",
    "sass-loader": "^6.0.6",
    "style-loader": "^0.19.0",
    "to-string-loader": "^1.1.5",
    "typescript": "^2.6.1",
    "url-loader": "^0.6.2",
    "web-animations-js": "^2.3.1",
    "webpack": "^3.8.1",
    "webpack-hot-middleware": "^2.20.0",
    "webpack-merge": "^4.1.1",
    "zone.js": "^0.8.18"
  },
  "devDependencies": {
    "@types/chai": "^4.0.4",
    "@types/jasmine": "^2.6.3",
    "chai": "^4.1.2",
    "jasmine-core": "^2.8.0",
    "karma": "^1.7.1",
    "karma-chai": "^0.1.0",
    "karma-chrome-launcher": "^2.2.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-webpack": "^2.0.5"
  },
  "scripts": {
    "dev-build": "node node_modules/webpack/bin/webpack.js --config webpack.config.vendor.js",
    "test": "karma start ClientApp/test/karma.conf.js"
  }
}

webpack.config.js

const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AotPlugin = require('@ngtools/webpack').AotPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;

module.exports = (env) => {
    // Configuration in common to both client-side and server-side bundles
    const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        stats: { modules: false },
        context: __dirname,
        resolve: { extensions: ['.js', '.ts'] },
        output: {
            filename: '[name].js',
            publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
        },
        module: {
            rules: [
                { test: /\.ts$/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader'] : '@ngtools/webpack' },
                { test: /\.html$/, use: 'html-loader?minimize=false' },
                { test: /\.css$/, use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize'] },
                { test: /\.scss$/, use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize', 'sass-loader'] },
                { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
            ]
        },
        plugins: [new CheckerPlugin()]
    };

    // Configuration for client-side bundle suitable for running in browsers
    const clientBundleOutputDir = './wwwroot/dist';
    const clientBundleConfig = merge(sharedConfig, {
        entry: { 'main-client': './ClientApp/boot.browser.ts' },
        output: { path: path.join(__dirname, clientBundleOutputDir) },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./wwwroot/dist/vendor-manifest.json')
            })
        ].concat(isDevBuild ? [
            // Plugins that apply in development builds only
            new webpack.SourceMapDevToolPlugin({
                filename: '[file].map', // Remove this line if you prefer inline source maps
                moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
            })
        ] : [
                // Plugins that apply in production builds only
                new webpack.optimize.UglifyJsPlugin(),
                new AotPlugin({
                    tsConfigPath: './tsconfig.json',
                    entryModule: path.join(__dirname, 'ClientApp/app/app.module#AppModule')
                })
            ])
    });

    return [clientBundleConfig];
};

webpack.config.vendor.js

const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const merge = require('webpack-merge');
const treeShakableModules = [
    '@angular/animations',
    '@angular/common',
    '@angular/compiler',
    '@angular/core',
    '@angular/forms',
    '@angular/http',
    '@angular/platform-browser',
    '@angular/platform-browser-dynamic',
    '@angular/router',
    'zone.js',
];
const nonTreeShakableModules = [
    'bootstrap',
    'core-js/client/shim',
    'web-animations-js',
    'event-source-polyfill',
    'jquery',
    '@swimlane/ngx-datatable/release/assets/icons.css',
    'ng2-toasty',
    'ng2-toasty/bundles/style-bootstrap.css',
    'ng2-charts',
    'ngx-bootstrap/modal',
    'ngx-bootstrap/tooltip',
    'ngx-bootstrap/popover',
    'ngx-bootstrap/dropdown',
    'ngx-bootstrap/carousel',
    'bootstrap-vertical-tabs/bootstrap.vertical-tabs.css',
    'bootstrap-toggle/css/bootstrap-toggle.css',
    'bootstrap-toggle/js/bootstrap-toggle.js',
    'bootstrap-select/dist/css/bootstrap-select.css',
    'bootstrap-select/dist/js/bootstrap-select.js',
    'bootstrap-datepicker/dist/css/bootstrap-datepicker3.css',
    'font-awesome/css/font-awesome.css'
];
const allModules = treeShakableModules.concat(nonTreeShakableModules);

module.exports = (env) => {
    const extractCSS = new ExtractTextPlugin('vendor.css');
    const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        stats: { modules: false },
        resolve: { extensions: ['.js'] },
        module: {
            rules: [
                { test: /\.(gif|png|woff|woff2|eot|ttf|svg)(\?|$)/, use: 'url-loader?limit=100000' }
            ]
        },
        output: {
            publicPath: 'dist/',
            filename: '[name].js',
            library: '[name]_[hash]'
        },
        plugins: [
            new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }), // Maps these identifiers to the jQuery package (because Bootstrap expects it to be a global variable)
            new webpack.ContextReplacementPlugin(/\@angular\b.*\b(bundles|linker)/, path.join(__dirname, './ClientApp')), // Workaround for https://github.com/angular/angular/issues/11580
            new webpack.ContextReplacementPlugin(/angular(\\|\/)core(\\|\/)@angular/, path.join(__dirname, './ClientApp')), // Workaround for https://github.com/angular/angular/issues/14898
            new webpack.IgnorePlugin(/^vertx$/) // Workaround for https://github.com/stefanpenner/es6-promise/issues/100
        ]
    };

    const clientBundleConfig = merge(sharedConfig, {
        entry: {
            // To keep development builds fast, include all vendor dependencies in the vendor bundle.
            // But for production builds, leave the tree-shakable ones out so the AOT compiler can produce a smaller bundle.
            vendor: isDevBuild ? allModules : nonTreeShakableModules
        },
        output: { path: path.join(__dirname, 'wwwroot', 'dist') },
        module: {
            rules: [
                { test: /\.css(\?|$)/, use: extractCSS.extract({ use: isDevBuild ? 'css-loader' : 'css-loader?minimize' }) }
            ]
        },
        plugins: [
            extractCSS,
            new webpack.DllPlugin({
                path: path.join(__dirname, 'wwwroot', 'dist', '[name]-manifest.json'),
                name: '[name]_[hash]'
            })
        ].concat(isDevBuild ? [] : [
            new webpack.optimize.UglifyJsPlugin()
        ])
    });

    return [clientBundleConfig];
}

【问题讨论】:

  • 你在使用 angular2-jwt 吗?
  • 这是一个 angular-cli 项目吗?你能添加你的 package.json
  • 不,它是一个 .core 2.0 项目,它一直工作到 angular 5 和 httpclientmodule 升级。下面的链接也与上面的答案相同,但它没有帮助,因为 httpclient 已经在使用它的构造函数中。
  • 不,它不是重复的,它们是不同的,它的答案在我身边已经是正确的,即使我有测试文件但没有测试文件,也会出现同样的问题

标签: angular typescript


【解决方案1】:

我的特殊问题是,当我在我的应用程序模块中正确包含 HttpClientModule 时,我正在注入 HttpClient 时导入了“错误”的 HttpClient,特别是来自 signalr 包的 HttpClient。

import { HttpClient } from '@aspnet/signalr';

因为自动完成发生时我没有注意,

我不得不假设其他一些人也遇到了类似的问题,而不是他们只是没有在他们的应用模块中导入 HttpClientModule。

【讨论】:

    【解决方案2】:

    第 1 步:在 app.module.ts 中导入 HttpClientModule

    import { HttpClientModule} from '@angular/common/http';
    

    第 2 步:在模块导入中添加 HttpClientModule

    @NgModule({
      declarations: [
        ...
      ],
      imports: [
        HttpClientModule
      ],
      providers: [
        ....
      ],
      bootstrap: [AppComponent]
    })
    

    【讨论】:

      【解决方案3】:

      HttpClient 出现错误,因此您缺少 HttpClientModule

      你应该像这样在app.module.ts文件中导入它-

      import { HttpClientModule } from '@angular/common/http';
      

      并像这样在NgModule Decorator 中提及它 -

      @NgModule({
      ...
      imports:[ HttpClientModule ]
      ...
      })
      

      希望它可以工作。 请参阅下图了解更多信息。

      【讨论】:

        【解决方案4】:

        在 app.module.ts -> import 部分下,您需要添加 HttpClientModule。下面是示例

        import { HttpClientModule } from '@angular/common/http';
        
        
            @NgModule({
              declarations: [
                AppComponent
              ],
              imports: [
                BrowserModule,
                BrowserAnimationsModule,
                HttpClientModule,  // This is where you need to add
                FormsModule,
            ...
        

        【讨论】:

          【解决方案5】:

          只需在 app.module.ts 文件的“导入”数组中添加 HttpClientModule

          ...
          import {HttpClientModule} from '@angular/common/http'; // add this line
          @NgModule({
            declarations: [
              AppComponent,
              HeaderComponent
            ],
            imports: [
              BrowserModule,
              HttpClientModule, //add this line
            ],
            providers: [],
            bootstrap: [AppComponent]
          })
          export class AppModule { }
          

          然后你可以通过构造函数注入在你的项目中使用HttpClient

            import {HttpClient} from '@angular/common/http';
            
            export class Services{
            constructor(private http: HttpClient) {}
          

          【讨论】:

            【解决方案6】:

            import 部分的 app.module.ts 文件中添加 HttpClientModule 解决了我的问题。

            【讨论】:

              【解决方案7】:

              转到app.module.ts

              导入import { HttpClientModule } from '@angular/common/http';

              在导入下添加HttpClientModule

              应该是这样的

              imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule,HttpClientModule]
              

              【讨论】:

                【解决方案8】:

                在我的例子中,我在子模块(不是根 AppModule)中使用服务,而 HttpClientModule 仅在模块中导入。

                所以我必须修改服务的默认范围,通过在 @Injectable 装饰器中将 'providedIn' 更改为 'any'。

                默认情况下,如果您使用 angular-cli 生成服务,则“providedIn”设置为“root”。

                希望这会有所帮助。

                【讨论】:

                • 为我工作..谢谢
                【解决方案9】:

                将使用 HTTPClient 的服务注入类后出现此错误。该类再次在服务中使用,因此它创建了循环依赖项。我可以编译带有警告的应用程序,但在浏览器控制台中发生了错误

                “没有 HttpClient 的提供者!(MyService -> HttpClient)”

                它破坏了应用程序。

                这行得通:

                import { HttpClient, HttpClientModule, HttpHeaders } from '@angular/common/http';
                import { MyClass } from "../classes/my.class";
                
                @Injectable()
                export class MyService {
                  constructor(
                    private http: HttpClient
                  ){
                    // do something with myClass Instances
                  }      
                }
                .
                .
                .
                export class MenuItem {
                  constructor(
                
                  ){}
                }
                

                这会破坏应用程序

                import { HttpClient, HttpClientModule, HttpHeaders } from '@angular/common/http';
                import { MyClass } from "../classes/my.class";
                
                @Injectable()
                export class MyService {
                  constructor(
                    private http: HttpClient
                  ){
                    // do something with myClass Instances
                  }      
                }
                .
                .
                .
                import { MyService } from '../services/my.service';
                export class MyClass {
                  constructor(
                    let injector = ReflectiveInjector.resolveAndCreate([MyService]);
                    this.myService = injector.get(MyService);
                  ){}
                }
                

                在 MyClass 中注入 MyService 后,我收到了循环依赖警告。 CLI 仍然编译时出现此警告,但应用程序不再工作,并且在浏览器控制台中给出了错误。所以在我的情况下,它不需要对@NgModule 做任何事情,而是使用循环依赖。如果您的问题仍然存在,我建议解决区分大小写的命名警告。

                【讨论】:

                  【解决方案10】:

                  为了解决这个问题,HttpClient 是 Angular 通过 HTTP 与远程服务器通信的机制。

                  为了使HttpClient 在应用程序中随处可见,

                  1. 打开根AppModule

                  2. @angular/common/http 导入HttpClientModule

                    import { HttpClientModule } from '@angular/common/http';

                  3. 将其添加到@NgModule.imports 数组中。

                    imports:[HttpClientModule, ]

                  【讨论】:

                  • 谢谢!你省了我在这个问题上花费更多时间。竖起大拇指!
                  • 这为我解决了问题。我不小心把我的放在了声明中。
                  • 只在app.module中导入,其他地方都没有,子模块中也没有
                  • 太糟糕了,OP 没有花一秒钟时间接受这个作为答案......
                  • 我很高兴地宣布此解决方案已由 Assistant medium.com/@tomaszs2/… 提供
                  【解决方案11】:

                  在我的情况下,我发现一旦我重建了它工作的应用程序。

                  我已按照之前帖子中的说明导入了 HttpClientModule,但我仍然收到错误消息。我停止了服务器,重新构建了应用程序 (ng serve),它运行正常。

                  【讨论】:

                    【解决方案12】:

                    在我的例子中,当使用位于 npm 包中的 Angular 模块中的服务时发生错误,该服务需要注入 HttpClient。安装 npm 包时,由于version conflict handling of npmengi-sdk-client 是包含服务的模块),在包目录中创建了一个重复的node_modules 目录:

                    显然,对HttpClient 的依赖没有正确解析,因为HttpClientModule 的位置注入到服务中(位于重复的node_modules 目录中)和注入app.module 的位置(正确的@987654331 @) 不匹配。

                    由于错误的npm install 调用,我在包含重复的node_modules 目录的其他设置中也遇到了此错误。

                    这种有缺陷的设置也会导致所描述的运行时异常No provider for HttpClient!

                    TL;DR;检查重复的node_modules 目录,如果没有 其他解决方案有效!

                    【讨论】:

                      【解决方案13】:

                      我遇到了同样的问题,然后在我的 app.module.ts 我以这种方式更新了文件,

                      import { HttpModule } from '@angular/http';
                      import { HttpClientModule } from '@angular/common/http';
                      

                      在我的 @NgModule imports[]array 中的同一个文件 (app.module.ts) 中,我是这样写的,

                      HttpModule,
                      HttpClientModule
                      

                      【讨论】:

                        【解决方案14】:

                        我有类似的问题。对我来说,解决方法是在 HttpClient 模块之前导入 HttpModule:

                        import { HttpModule } from '@angular/http';
                        import { HttpClientModule } from '@angular/common/http';
                        .
                        .
                        .
                        imports: [
                          BrowserModule,
                          HttpModule,
                          HttpClientModule
                        ],
                        

                        【讨论】:

                          【解决方案15】:

                          我遇到了同样的问题,有趣的是我同时打开了两个项目,我更改了错误的 app.modules.ts 文件。

                          首先,检查一下。

                          更改后将以下代码添加到 app.module.ts 文件

                          import { HttpClientModule } from '@angular/common/http';
                          

                          然后将以下内容添加到 app.module.ts 文件中的 imports 数组中

                            imports: [
                              HttpClientModule,....
                            ],
                          

                          现在你应该没事了!

                          【讨论】:

                            【解决方案16】:

                            在 app.module.ts 的导入和提供程序中添加 HttpModuleHttpClientModule 解决了这个问题。 导入 -> import {HttpModule} from "@angular/http"; import {HttpClientModule} from "@angular/common/http";

                            【讨论】:

                            • 我也有同样的问题。我查看了 App_modules,但路径 @angular-->common 中没有 http 目录我运行“npm update”我正在使用 Windows 8.i,nodejs 版本 9.7.1。我正在阅读 Valerio de Sanctis 的书……它会是什么?谢谢
                            • 以管理员模式运行'npm i'。
                            【解决方案17】:

                            我发现了更棘手的问题。请在您的 app.module.ts 文件中导入 HttpClientModule,如下所示:

                            import { BrowserModule } from '@angular/platform-browser';
                            import { NgModule } from '@angular/core';
                            
                            import { AppComponent } from './app.component';
                            import { HttpClientModule } from '@angular/common/http';
                            
                            @NgModule({
                              declarations: [
                                AppComponent
                            ],
                            
                            imports: [
                                BrowserModule,
                                HttpClientModule
                              ],
                              providers: [],
                              bootstrap: [AppComponent]
                            })
                            export class AppModule { }
                            

                            【讨论】:

                              【解决方案18】:

                              通过进行以下更改,我也面临类似的问题,它对我有用

                              在 app.modules.ts 中

                              import {HttpClientModule} from '@angular/common/http' 
                              

                              并在相应的服务类中

                              import { HttpClient } from '@angular/common/http'
                              

                              构造函数应该如下所示

                              constructor(private http: HttpClient, private xyz: xyzService) {}
                              

                              在测试文件中

                              import { HttpClientTestingModule } from '@angular/common/http/testing'
                              
                                beforeEach(() => TestBed.configureTestingModule({
                                  imports: [HttpClientTestingModule]
                                }));
                              

                              【讨论】:

                              • 在 app.module.ts 上导入 HttpClientModule 不足以解决问题,但无论如何我都赞成你提醒我错过了什么。
                              • 导入 HttpClientTestingModule 解决了规范中的问题
                              【解决方案19】:

                              我有同样的问题。浏览并解决问题后找到以下解决方案

                              import { HttpModule } from '@angular/http';
                              import { HttpClientModule } from '@angular/common/http';
                              
                              imports: [
                                HttpModule,
                                HttpClientModule
                              ]
                              

                              在 app.module.ts 中导入 HttpModuleHttpClientModule 并像上面提到的那样添加到导入中。

                              【讨论】:

                              • 使用 HttpModule(已弃用)和 HttpClientModule(替换 HttpModule)没有意义
                              • 是的。只需导入 HttpClientModule。
                              【解决方案20】:

                              您收到 HttpClient 错误,因此您缺少 HttpClientModule。

                              你应该像这样在 app.module.ts 文件中导入它 -

                              import { HttpClientModule } from '@angular/common/http';
                              

                              并像这样在 NgModule 装饰器中提及它 -

                              @NgModule({
                              ...
                              imports:[ HttpClientModule ]
                              ...
                              })
                              

                              如果这仍然不起作用,请尝试清除浏览器的 cookie 并尝试重新启动服务器。希望它可以工作,我遇到了同样的错误。

                              【讨论】:

                              • 将 HttpClientModule 添加到导入解决了这个问题,因为它的值没有被使用,谢谢@Vivek kushwaha
                              【解决方案21】:

                              你没有在你的模块中提供提供者:

                              <strike>import { HttpModule } from '@angular/http';</strike>
                              import { HttpClientModule, HttpClient } from '@angular/common/http';
                              
                              @NgModule({
                                imports: [
                                  BrowserModule,
                                  HttpClientModule,
                                  BrowserAnimationsModule,
                                  FormsModule,
                                  AppRoutingModule
                                ],
                                providers: [ HttpClientModule, ... ]
                                // ...
                              })
                              export class MyModule { /* ... */ }
                              

                              在测试中使用 HttpClient

                              在运行 ng test 并收到“No provider for HttpClient”错误时,您需要将 HttpClientTestingModule 添加到 TestBed 配置中:

                              // Http testing module and mocking controller
                              import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
                              
                              // Other imports
                              import { TestBed } from '@angular/core/testing';
                              import { HttpClient, HttpErrorResponse } from '@angular/common/http';
                              
                              describe('HttpClient testing', () => {
                                let httpClient: HttpClient;
                                let httpTestingController: HttpTestingController;
                              
                                beforeEach(() => {
                                  TestBed.configureTestingModule({
                                    imports: [ HttpClientTestingModule ]
                                  });
                              
                                  // Inject the http service and test controller for each test
                                  httpClient = TestBed.get(HttpClient);
                                  httpTestingController = TestBed.get(HttpTestingController);
                                });
                              
                                it('works', () => {
                                });
                              });
                              

                              【讨论】:

                              • 不,这没有记录应该将 httpclientmodule 添加到提供程序列表中。但无论如何,我也尝试了你的答案来确定,但正如预期的那样,将其添加到提供者列表后,同样的错误仍然存​​在。
                              • 我猜应该将“HttpClientModule”添加到导入中,而不是提供者
                              • 我必须将imports: [HttpClientTestingModule] 添加到我的TestBed.configureTestingModule 以消除此错误在测试中
                              • @YaroslavStavnichiy 评论是我在 Jasmine 中遇到的问题的答案。
                              • 从 '@angular/common/http/testing' 导入 { HttpClientTestingModule, HttpTestingController };
                              【解决方案22】:

                              只导入HttpModuleHttpClientModule

                              import { HttpModule } from '@angular/http';
                              import { HttpClientModule } from '@angular/common/http';
                              

                              不需要HttpClient

                              【讨论】:

                                【解决方案23】:

                                在 angular github 页面中,讨论了这个问题并找到了解决方案。 https://github.com/angular/angular/issues/20355

                                【讨论】:

                                • 我在 Angular 5 的单元和集成测试中使用了这个链接,wleite,s comment 在页面底部解决这个问题
                                猜你喜欢
                                • 2019-06-25
                                • 2019-12-25
                                • 2018-03-16
                                • 1970-01-01
                                • 2019-11-23
                                • 2018-01-31
                                • 2022-10-15
                                • 1970-01-01
                                相关资源
                                最近更新 更多