Angular6:未捕获的错误:无法解析HttpService的所有参数:(?)

时间:2018-07-12 10:53:17

标签: angular

我正在尝试使用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 { }

非常感谢能帮助我解决这个问题的所有人:)

1 个答案:

答案 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) { 
}