我正在使用Angular 7,并且具有此文件夹结构
src
app
app.component.css
app.component.html
app.component.spec.ts
app.component.ts
app.module.ts
component.service.spec.ts
component.service.ts
在我的src / app / component.service文件中,
import { Injectable } from '@angular/core';
import { HttpModule } from '@angular/http';
@Injectable({
providedIn: 'root'
})
export class ComponentService {
private apiUrl = 'http://localhost:8080/todo/';
constructor(private http: Http) {
}
findAll(): Promise<Array<AppComponent>> {
return this.http.get(this.apiUrl + "/list")
.toPromise()
.then(response => response.json() as Todo[])
.catch(this.handleError);
}
...
但是我反复遇到导入错误
ERROR in src/app/component.service.ts(9,29): error TS2304: Cannot find name 'Http'.
我在服务中包含了HttpModule,那么我还缺少什么才能使它正确包含?
答案 0 :(得分:1)
您的问题是您尚未导入要在构造函数中注入的Http
类。
但是,您应该知道自Angular 4.3以来,我们得到了HttpClient
类作为Http类的改进。
您应该从HttpClient
导入Http
而不是@angular/common/http
即
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ComponentService {
private apiUrl = 'http://localhost:8080/todo/';
constructor(private http: HttpClient) {
}
findAll(): Promise<Array<AppComponent>> {
return this.http.get(this.apiUrl + "/list")
.toPromise()
.then(response => response.json() as Todo[])
.catch(this.handleError);
}
...