我有一个组件和服务,我尝试在组件中注入服务(ListUserService)。 导入服务后,我请求它,但出现错误,当我删除该服务后,它会正常工作吗?
import { Component, OnInit } from '@angular/core';
import {ListUserService} from './list-user.service';
@Component({
selector: 'app-list-user',
templateUrl: './list-user.component.html',
styleUrls: ['./list-user.component.scss'],
providers: [ListUserService]
})
export class ListUserComponent implements OnInit {
constructor(private listUserService: ListUserService) {
console.log(this.listUserService);
}
}
这是服务:
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ListUserService {
constructor(public http: HttpClient) {
this.http.get(`http://localhost:8080/user/getUsers/`)
.subscribe(response => {
console.log(response);
});
}
}
这是错误: 错误
错误:StaticInjectorError(AppModule)[ListUserService-> HttpClient]: StaticInjectorError(平台:核心)[ListUserService-> HttpClient]: NullInjectorError:没有HttpClient的提供程序!
这是文件app.module.ts
import {HttpClient} from '@angular/common/http';
import {AppRoutingModule} from './app-routing.module';
import {AppComponent} from './app.component';
import {ListUserComponent} from './list-user/list-user.component';
import {ListUserService} from './list-user/list-user.service';
@NgModule({
declarations: [AppComponent, ListUserComponent],
entryComponents: [],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
providers: [
HttpClient,
StatusBar,
SplashScreen,
ListUserService,
{provide: RouteReuseStrategy, useClass: IonicRouteStrategy}
],
bootstrap: [AppComponent]
})
export class AppModule {
}
答案 0 :(得分:2)
您未能在导入的app.module.ts
import { ListUserComponent } from './list-user/list-user.component';
import { ListUserService } from './list-user/list-user.service';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [AppComponent, ListUserComponent],
entryComponents: [],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule,HttpClientModule],
providers: [
StatusBar,
SplashScreen,
ListUserService,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})
export class AppModule {}
答案 1 :(得分:0)
将您的服务添加到app.module.ts中的providers: [ListUserService]
https://angular.io/guide/ngmodules
编辑:HttpClient必须同时添加到providers: [ListUserService, HttpClient]
和import {HttpClient} from '@angular/common/http';