[英]Angular6: Uncaught Error: Can't resolve all parameters for HttpService: (?)
I am trying to read data from a web service using the HttpClientModule . 我正在尝试使用HttpClientModule从Web服务读取数据。 I have created my own class HttpService where I want to do all the operations related to http.
我创建了自己的HttpService类,我想在其中执行与http相关的所有操作。 However, I am getting an error when creating the HttpService object.
但是,创建HttpService对象时出现错误。
Code in my main class: 我的主要课程中的代码:
httpS:HttpService;
this.httpS.getHttpData(this.urlS).subscribe(data => {
this.posts = data
});
HttpService class: 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: 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 { }
Would be very grateful for everyone who can help me with this problem :) 非常感谢所有可以帮助我解决这个问题的人:)
You need to add @Injectable()
to your HttpService
, since you are using Dependency Injection
(HttpClient) in your service 您需要添加
@Injectable()
到您的HttpService
,因为你正在使用Dependency Injection
你的服务(HttpClient的)
@Injectable()
export class HttpService {
constructor(private httpC: HttpClient) { }
getHttpData(urlString: string): Observable<Post[]> {
console.log(urlString);
return this.httpC.get<Post[]>(urlString);
}
}
EDIT : 编辑:
Well, as @ AJT_82 pointed out, You should add HttpService
as a DI in your component, instead of creating a direct reference httpS:HttpService
. 好吧,正如@ AJT_82指出的那样,您应该在组件中添加
HttpService
作为DI,而不是创建直接引用httpS:HttpService
。
Add this to your component 将此添加到您的组件
constructor (private httpS : HttpService) {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.