问题
im using ionic 2 and i create a simple service
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
@Injectable()
export class EliteApi {
private baseUrl="https://myurl.com";
constructor(private http:Http) { }
getTournaments(){
return new Promise(resolve =>{
this.http.get(this.baseUrl + 'tournaments.json').subscribe(res => resolve(res.json()));
});
}
}
then i import it on app.component.ts like this to register the service
import { EliteApi } from './shared/shared';
import {Http} from "@angular/http";
@Component({
templateUrl: 'app.html',
providers: [EliteApi,Http]
})
after that on my page i import the service
import { EliteApi } from '../../app/shared/shared';
and on the event loaded i wrote this to get the json data
ionViewLoaded(){
this.eliteApi.getTournaments().then(data => this.tournaments = data);
}
it gives me exception says No provider for ConnectionBackend!
i tried as some question similar here says put the service on providers as this
@NgModule({ providers: [ EliteApi
but also the same error
回答1:
Have you import the HttpModule
in your App
module?
import { HttpModule } from '@angular/http';
@NgModule({
imports: [HttpModule]
})
回答2:
the problem solved when I type my code in the event ionViewWillLoad
or ionViewDidLoad
not ionViewLoaded
also the code works fine when I import HttpModule on app.component.ts
import { HttpModule} from "@angular/http";
and add it to providers like this
providers: [EliteApi,HttpModule]
回答3:
You also need to inject the service in constructor before using it like below:
constructor(public eliteApi:EliteApi){ }
来源:https://stackoverflow.com/questions/41389126/no-provider-for-connectionbackend-for-ionic-2