Error: No provider for http in constructor paramet

2020-04-19 06:09发布

问题:

I'm following a tutorial in Portuguese that teaches how to build your first Ionic application.

After installing npm, node.js, angular, Ionic and Cordova using last versions I started writing the code. The code itself it's really simple:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage {

  public feeds: Array<string>;
  private url: string = "https://www.reddit.com/new.json";

  constructor(public navCtrl: NavController, public http: Http) {

    this.http.get(this.url).map(res => res.json()).subscribe(data => {
        this.feeds = data.data.children;
      });
  }
}`

I'm basically consuming the Reddit's API JSON, which can be accessed using the link in "url" variable and it's supposed to return a huge JSON, transform it and store in "feeds". The problem is whenever I serve this ionic app I get this error:

I already tried to figure this problem out and discovered that if I erase everything that's inside the constructor I still get the error but if I erase "public http: Http" which is a parameter for the constructor the error is gone.

Looking for solutions I saw someone suggestion to add providers to @Component but the tutorial does not say anything about that.

I already tried to reinstall everything but i still get the error.

What you have to do to recreate the error:

  • Install npm at latest version;
  • Install node.js at latest stable version;
  • Install angular at latest version using npm;
  • Install ionic (2.2.2) and cordova (6.5.0) latest version using npm;
  • Create an app using: ionic start MyReader blank --v2 --appname "Best Reader Ever" --id "com.tableless.myreader"
  • Change MyReader/src/pages/home/home.ts content to the script above.

Also if you do like to take a look at the tutorial itself, the link is: https://tableless.com.br/criando-uma-aplicacao-movel-com-ionic-2-e-angular-2-em-dez-passos/

回答1:

Use the below code

import {HTTP_PROVIDERS} from '@angular/http';

provider : [ HTTP_PROVIDERS, ....


 ]

The above answer was deprecated since angular4. However As I said in the comment,

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

imports: [ HttpModule ]


回答2:

SOLUTION: HTTP_PROVIDERS were removed from angular2 and were replaced by: HttpModule.

All I had to do was add:

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

To src/app/app.module.ts and then:

imports: [
  BrowserModule,
  HttpModule,
  IonicModule.forRoot(MyApp)
],

And done. Thank you so much for everyone.