尝试使用* ngFor将JSON数据加载到表中时发生错误NullInjectorError:StaticInjectorError(AppModule)

时间:2019-11-16 11:26:37

标签: angular typescript

我遇到以下错误:

  

ERROR NullInjectorError:   StaticInjectorError(AppModule)[DisplayLeaveRequestComponent->   DisplayLeaveRequestService]:StaticInjectorError(平台:   核心)[DisplayLeaveRequestComponent-> DisplayLeaveRequestService]

Error Message

display-leave-request.component.ts

import { Component, OnInit } from "@angular/core";
import { DisplayLeaveRequestService } from "./display-leave-request.service";

@Component({
  selector: "app-display-leave-request",
  templateUrl: "./display-leave-request.component.html",
  styleUrls: ["./display-leave-request.component.css"]
})
export class DisplayLeaveRequestComponent implements OnInit {
  public leaveRequestData = [];

  constructor(private _fetchedData: DisplayLeaveRequestService) {}

  ngOnInit() {
    this._fetchedData
      .getLeaveRequests()
      .subscribe(data => (this.leaveRequestData = data));
  }
}

display-leave-request.service

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { ILeaveRequestData } from "./display-leave-request.interface";
import { Observable } from "rxjs";

@Injectable()
export class DisplayLeaveRequestService {
  private _URL = "../../assets/data/dataForTable.json";

  constructor(private http: HttpClient) {}

  getLeaveRequests(): Observable<ILeaveRequestData[]> {
    return this.http.get<ILeaveRequestData[]>(this._URL);
  }
}

display-leave-request.interface.ts

export interface ILeaveRequestData {
  leaveType: string;
  reasonForLeave: string;
  noOfDaysApplied: string;
  submittedOn: string;
  approvedOn: string;
  approvedBy: string;
}

app.module

import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { HttpClientModule } from "@angular/common/http";

import { AppComponent } from "./app.component";
import { DisplayLeaveRequestComponent } from "./display-leave-request/display-leave-request.component";

@NgModule({
  declarations: [AppComponent, DisplayLeaveRequestComponent],
  imports: [BrowserModule, HttpClientModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

1 个答案:

答案 0 :(得分:0)

将DisplayLeaveRequestComponent组件添加到app.module.ts中的提供程序

import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { HttpClientModule } from "@angular/common/http";

import { AppComponent } from "./app.component";
import { DisplayLeaveRequestComponent } from "./display-leave-request/display-leave-request.component";

@NgModule({
  declarations: [AppComponent, DisplayLeaveRequestComponent],
  imports: [BrowserModule, HttpClientModule],
  providers: [DisplayLeaveRequestService ],
  bootstrap: [AppComponent]
})
export class AppModule {}