这是我的HttpService.ts
import { Injectable } from "@angular/core";
import { Http, Response } from "@angular/http";
import 'rxjs/add/operator/map';
@Injectable()
export class HttpService {
constructor (private http: Http) {}
getData() {
return this.http.get('http://blog_api.org/v1/posts')
.map((response: Response) => response.json());
}
}
这是我的app.component.ts
import { Component } from '@angular/core';
import { HttpService } from '../app/services/HttpService'
@Component({
selector: 'my-app',
template: `Hello`,
})
export class AppComponent {
constructor (private httpService: HttpService) {};
ngOnInit() {
this.httpService.getData()
.subscribe(
data => console.log(data)
)
}
}
当我运行应用时,我收到错误:
EXCEPTION:没有HttpService的提供者!
答案 0 :(得分:1)
在AppModule中你应该这样做:
import {HttpService} from "...";
import {HttpModule} from "@angular/http";
@NgModule({
bootstrap: [...],
imports: [HttpModule],
declarations: [...],
entryComponents: [...],
providers: [HttpService]
})
export default class AppModule{}
答案 1 :(得分:0)
您必须在加载HttpService
。
app.component.ts
在您的情况下,当您使用app.component.ts
时,请在http
中提供app.module.ts
。类似的东西:
import { HttpService } from '../app/services/HttpService'
@NgModule({
...
providers: [
...
HttpService,
]
})
export class AppModule { }
答案 2 :(得分:0)
添加
@Component块中的提供者:[HttpService]