我正在尝试使用HttpClientModule从Web服务读取数据。我创建了自己的HttpService类,我想在其中执行与http相关的所有操作。 但是,创建HttpService对象时出现错误。
我的主班代码:
httpS:HttpService;
this.httpS.getHttpData(this.urlS).subscribe(data => {
this.posts = data
});
HttpService类:
import { Observable } from 'rxjs';
import { Post } from '../Interfaces/Post';
import { HttpClient } from '@angular/common/http';
export class HttpService {
constructor(private httpC: HttpClient) { }
getHttpData(urlString: string): Observable<Post[]> {
console.log(urlString);
return this.httpC.get<Post[]>(urlString);
}
}
AppModule.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { HttpService } from './classes/HttpService';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [HttpService],
bootstrap: [AppComponent]
})
export class AppModule { }
非常感谢能帮助我解决这个问题的所有人:)
答案 0 :(得分:0)
由于您在服务中使用了@Injectable()
(HttpClient),因此需要将HttpService
添加到Dependency Injection
中
@Injectable()
export class HttpService {
constructor(private httpC: HttpClient) { }
getHttpData(urlString: string): Observable<Post[]> {
console.log(urlString);
return this.httpC.get<Post[]>(urlString);
}
}
编辑:
好吧,正如@ AJT_82指出的那样,您应该在组件中添加HttpService
作为DI,而不是创建直接引用httpS:HttpService
。
将此添加到您的组件
constructor (private httpS : HttpService) {
}