【问题标题】:No provider for Http StaticInjectorError没有 Http StaticInjectorError 的提供者
【发布时间】:2018-05-09 14:27:10
【问题描述】:

我正在尝试从我的 api 中提取数据,并将其填充到我的 ionic 应用程序中,但是当我进入应填充数据的页面时它崩溃了。下面是我的两个 .ts 文件:

import { Component } from '@angular/core';

import { NavController, LoadingController } from 'ionic-angular';
import { RestService } from '../../providers/rest-service/rest-service';

@Component({
  selector: 'page-all-patients',
  templateUrl: 'all-patients.html',
  providers: [RestService]
})
export class AllPatientsPage {
  data: any;
  loading: any;

  constructor(public navCtrl: NavController, public restService: RestService, public loadingCtrl: LoadingController) {

    this.loading = this.loadingCtrl.create({
      content: `
        <ion-spinner></ion-spinner>`
    });
    this.getdata();
  }

  getdata() {
    this.loading.present();
    this.restService.getJsonData().subscribe(
      result => {
        this.data=result.data.children;
        console.log("Success: " + this.data);
      },
      err => {
        console.error("Error : " + err);
      },
      () => {
        this.loading.dismiss();
        console.log('getData completed');
     }
   );
 }
}

和其他文件:

import { Http } from '@angular/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';

/*
  Generated class for the RestServiceProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/

@Injectable()
export class RestService {

  constructor(public http: Http) {
    console.log('Hello RestServiceProvider Provider');
  }

  getJsonData() {
    // return Promise.resolve(this.data);

     return this.http.get('url').map(res => res.json());
   }

}

我也尝试过使用 HttpModule,但这是一个致命错误。报错如下:

Error: Uncaught (in promise): Error: StaticInjectorError[Http]: 
  StaticInjectorError[Http]: 
    NullInjectorError: No provider for Http!
Error: StaticInjectorError[Http]: 
  StaticInjectorError[Http]: 
    NullInjectorError: No provider for Http!
    at _NullInjector.get (http://lndapp.wpi.edu:8100/build/vendor.js:1276:19)

我不确定为什么没有提供程序错误,因为这是通过 ionic 框架创建的提供程序

【问题讨论】:

    标签: angular typescript ionic-framework


    【解决方案1】:

    为了在您的应用中使用 Http,您需要将 HttpModule 添加到您的 app.module.ts:

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule, ErrorHandler } from '@angular/core';
    import { HttpModule } from '@angular/http';
    ...
      imports: [
        BrowserModule,
        HttpModule,
        IonicModule.forRoot(MyApp),
        IonicStorageModule.forRoot()
      ]
    

    编辑

    正如下面评论中提到的,HttpModule 现在是 deprecated,请使用 import { HttpClientModule } from '@angular/common/http';确保 HttpClientModule 在您的 imports:[] 数组中

    【讨论】:

    • 我已将此添加到 app.module.ts,但现在出现错误:Cannot find name 'IonicStorageModule'.
    • 你必须做 import import { IonicStorageModule } from '@ionic/storage'; .以上只是一个样例,不需要的可以去掉
    • 我确实有那个,但是当我删除它时,它可以工作。谢谢!
    • HttpModule 现在似乎已被弃用,请改用 import { HttpClientModule } from '@angular/common/http'; 并确保在您的导入中使用 HttpClientModule:[] 数组。
    • 确保将您的服务也包含在 [providers] 列表中,如下面的答案stackoverflow.com/a/52791929/2023941 所示,然后重新启动编译器。
    【解决方案2】:

    更新:Angular v6+

    对于从旧版本(Angular v2 - v5)转换而来的应用程序:HttpModule 现已弃用,您需要将其替换为 HttpClientModule,否则您也会收到错误消息。

    1. 在您的 app.module.ts 中,将 import { HttpModule } from '@angular/http'; 替换为新的 HttpClientModule import { HttpClientModule} from "@angular/common/http"; 注意:请务必通过删除旧的 @987654325 来更新模块 imports[] 数组@ 并将其替换为新的 HttpClientModule
    2. 在您使用 HttpModule 替换的任何服务中 import { Http } from '@angular/http'; 与新的 HttpClient import { HttpClient } from '@angular/common/http';
    3. 更新您处理 Http 响应的方式。例如 - 如果您的代码看起来像这样

      http.get('people.json').subscribe((res:Response) =&gt; this.people = res.json());

    上面的代码示例会导致错误。我们不再需要解析响应,因为它已经在配置对象中以 JSON 形式返回。

    订阅回调将数据字段复制到组件的配置对象中,该对象在组件模板中进行数据绑定以进行显示。

    有关更多信息,请参阅 - Angular HttpClientModule - Official Documentation

    【讨论】:

    • 收到错误NullInjectorError: No provider for HttpClient!
    【解决方案3】:

    您还需要将 HttpClientModule 从 Angular '@angular/common/http' 导入主 AppModule 以发出 HTTP 请求。

    app.module.ts

    import { HttpClientModule } from '@angular/common/http';
    import { ServiceService } from '../../../services/service.service';
    
    @NgModule({
       imports: [
           HttpClientModule
       ],
       providers: [
           ServiceService
       ]
    })
    export class AppModule {...}
    

    【讨论】:

      【解决方案4】:

      将这两个文件添加到你的app.module.ts

      import { FileTransfer } from '@ionic-native/file-transfer';
      import { File } from '@ionic-native/file';
      

      然后在提供者中声明这些。

      providers: [
          Api,
          Items,
          User,
          Camera,
          File,
          FileTransfer];
      

      这对我有用。

      【讨论】:

      • 您能否通过选择代码块并单击编辑工具栏中的{} 图标来标记代码块?谢谢! :)
      【解决方案5】:

      我在一个 Angular 项目中(不幸的是)通过tsconfig.json 使用源代码包含来连接不同的代码集合。我遇到了类似的StaticInjector 服务错误(例如,顶部示例中的RestService),当在模块中提供受影响的服务时,我能够通过在deps 数组中列出服务依赖项来修复它,例如示例:

      import { HttpClient } from '@angular/common/http';
      import { NgModule } from '@angular/core';
      import { HttpModule } from '@angular/http';
      import { RestService } from 'mylib/src/rest/rest.service';
      ...
      @NgModule({
        imports: [
          ...
          HttpModule,
          ...
        ],
        providers: [
          {
            provide: RestService,
            useClass: RestService,
            deps: [HttpClient] /* the injected services in the constructor for RestService */
          },
        ]
        ...
      

      【讨论】:

      • 好一个!您能否解释一下“通过 tsconfig.json 包含源代码”??
      【解决方案6】:

      在 ionic 4.6 中,我使用以下技术并且它有效。我正在添加这个答案,以便如果有人在较新的 ionic 版本应用程序中遇到类似问题,它可能会对他们有所帮助。

      i) 打开 app.module.ts 并添加以下代码块以导入 HttpModule 和 HttpClientModule

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

      ii) 在@NgModule 导入部分添加以下行:

      HttpModule,
      HttpClientModule,
      

      所以,在我的@NgModule 中,看起来像这样:

      @NgModule({
        declarations: [AppComponent ],
        entryComponents: [ ],
        imports: [
          BrowserModule,
          HttpModule,
          HttpClientModule,
          IonicModule.forRoot(),
          AppRoutingModule, 
        ],
        providers: [
          StatusBar,
          SplashScreen,
          { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
        ],
        bootstrap: [AppComponent]
      })
      

      就是这样!

      【讨论】:

        【解决方案7】:

        我试图解决这个问题大约一个小时,然后才决定重新启动服务器。只是看到问题已修复。

        如果您对 APP 模块进行了更改,但问题仍然存在,请停止服务器并再次尝试运行 serve 命令。

        使用 ionic 4 和 angular 7

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-11-29
          • 1970-01-01
          • 2020-08-15
          • 2017-01-05
          • 2018-04-24
          • 2022-11-25
          • 2019-06-22
          • 2018-10-19
          相关资源
          最近更新 更多