No hay proveedor para Http StaticInjectorError
Estoy tratando de extraer los datos de mi api y rellenarlos en mi aplicación ionic, pero se bloquea cuando entro en la página en la que se deben rellenar los datos. Abajo están mis dos .archivos 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');
}
);
}
}
Y el otro archivo:
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());
}
}
También he intentado usar el HttpModule, pero es un error fatal. El error es como se muestra:
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)
No estoy seguro de por qué hay un error de no proveedor, ya que este es el proveedor creado a través de ionic framework
3 answers
Para usar Http en su aplicación, deberá agregar el HttpModule a su aplicación.módulo.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()
]
EDITAR
Como se menciona en el comentario a continuación, HttpModule
es deprecated
ahora, usa import { HttpClientModule } from '@angular/common/http'
; Asegúrese de HttpClientModule
en su imports:[]
array
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-03 02:01:09
Actualización: Angular v6 +
Para Aplicaciones convertidas de versiones anteriores (Angular v2 - v5): HttpModule ahora está obsoleto y debe reemplazarlo con HttpClientModule o también obtendrá el error.
- En su
app.module.ts
reemplaceimport { HttpModule } from '@angular/http';
con el nuevo HttpClientModuleimport { HttpClientModule} from "@angular/common/http";
Nota: Asegúrese de actualizar el array modulesimports[]
eliminando el antiguoHttpModule
y reemplazándolo con el nuevoHttpClientModule
. - En cualquiera de sus servicios que utilizan HttpModule reemplazar
import { Http } from '@angular/http';
con el nuevo HttpClientimport { HttpClient } from '@angular/common/http';
-
Actualice cómo maneja su respuesta Http. Por ejemplo, si tiene un código que se parece a este
http.get('people.json').subscribe((res:Response) => this.people = res.json());
El ejemplo de código anterior resultará en un error. Ya no necesitamos analizar la respuesta, porque ya vuelve como JSON en el objeto config.
La devolución de llamada de suscripción copia los campos de datos en el objeto config del componente, que está enlazado a datos en el componente plantilla para visualización.
Para obtener más información, consulte el - Angular HttpClientModule-Documentación oficial
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-17 19:01:46
Agregue estos dos archivos en su app.module.ts
import { FileTransfer } from '@ionic-native/file-transfer';
import { File } from '@ionic-native/file';
Después de eso declarar estos en el proveedor..
providers: [
Api,
Items,
User,
Camera,
File,
FileTransfer];
Esto es trabajo para mí.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-21 10:32:38