Angular 5 Uncaught(承诺):错误:StaticInjectorError(AppModule)

时间:2018-05-04 15:34:11

标签: c# asp.net-mvc promise kendo-grid angular5

我正在Angular 5中进行此开发 Visual Studio 2017版本15.6.7 TargetFramework - netcoreapp2.0 rxjs:5.5.10

我无法摆脱这个错误:

  

错误错误:未捕获(在承诺中):错误:   StaticInjectorError(AppModule)[VtoReportComponent - > VTOS]:   StaticInjectorError(Platform:core)[VtoReportComponent - > VTOS]:   NullInjectorError:没有Vtos的提供者!

这里是vto.service.ts

import { Component, OnInit } from '@angular/core';
import { Http, HttpModule } from '@angular/http';
import { Observable } from 'rxjs';
import { GroupDescriptor, DataSourceRequestState, DataResult, process, State } from '@progress/kendo-data-query';
import { ExcelExportData } from '@progress/kendo-angular-excel-export';
import { aggregateBy, SortDescriptor, orderBy } from '@progress/kendo-data-query';
import { Vtos } from '../../services/vto.service';

import {
  GridComponent,
  GridDataResult,
  DataStateChangeEvent
} from '@progress/kendo-angular-grid';

@Component({
  selector: 'app-vto-report',
  templateUrl: './vto-report.component.html',
  styleUrls: ['./vto-report.component.css']
})
export class VtoReportComponent {
  public multiple = false;
  public allowUnsort = true;
  public gridData: GridDataResult;
  public state: DataSourceRequestState = {
    skip: 0,
    take: 5,
  };

  constructor(private vtos: Vtos) {
      this.vtos.getVtos(this.state).subscribe(r => this.gridData = r);
  }

  public dataStateChange(state: DataStateChangeEvent): void {
    this.state = state;
    this.vtos.getVtos(state)
      .subscribe(r => this.gridData = r);
  }

vto.service.html

<kendo-grid [data]="gridData"
            [pageSize]="state.take"
            [skip]="state.skip"
            [sort]="state.sort"
            [sortable]="true"
            [pageable]="true"
            [scrollable]="'scrollable'"
            [groupable]="true"
            [group]="state.group"
            [filterable]="true"
            [filter]="state.filter"
            (dataStateChange)="dataStateChange($event)"
            [height]="370">
  <kendo-grid-column field="EmployeeID" title="Employee ID" [width]="250"></kendo-grid-column>
  <kendo-grid-column field="ReportDate" title="Report Date" width="240" filter="date" format="{0:MM/dd/yyyy}"></kendo-grid-column>
  <kendo-grid-column field="BeginTime" title="Begin Time"></kendo-grid-column>
  <kendo-grid-column field="EndTime" title="End Time"></kendo-grid-column>
  <kendo-grid-column field="TotalHours" title="Total Hours" filter="numeric"></kendo-grid-column>

  <kendo-grid-column field="VTOby" title="VTOby">

  </kendo-grid-column>
  <kendo-grid-column field="Timestamp" title="Time stamp"></kendo-grid-column>
</kendo-grid>

VTO-service.ts

import { Injectable } from '@angular/core';
import { VTO } from './vto';
import { Http, HttpModule } from '@angular/http';
import { Observable } from 'rxjs';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { Location, LocationStrategy, PathLocationStrategy } from '@angular/common';
import {
  toDataSourceRequestString,
  translateDataSourceResultGroups,
  translateAggregateResults,
  DataResult,
  DataSourceRequestState
} from '@progress/kendo-data-query';
import 'rxjs/add/operator/map';
import { GridDataResult, DataStateChangeEvent } from '@progress/kendo-angular-grid';

@Injectable()
export class Vtos{
  private vtoUrl = location.href.replace(location.hash, '') + '/home/getVtos';

  constructor(private http: Http) { }

  public getVtos(state: DataSourceRequestState): Observable <DataResult> {
    const queryStr = `${toDataSourceRequestString(state)}`; //serialize the state
    const hasGroups = state.group && state.group.length;

    return this.http
      .get(`${this.vtoUrl}?${queryStr}`) //send the state to the server
      .map(response => response.json())
      .map(({ data, total/*, aggregateResults*/ }) => // process the response
        (<GridDataResult>{
          //if there are groups convert them to compatible format
          data: hasGroups ? translateDataSourceResultGroups(data) : data,
          total: total,
          // convert the aggregates if such exists
          //aggregateResult: translateAggregateResults(aggregateResults)
        })
      )
  }
}

HomeController.cs

public JsonResult GetVtos()
{
  var data = Vto.GetVtos();
  return Json(data);
}

Vto.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using VTO.DTO;
using System.Data;
using System.Data.SqlClient;
using System.Web;

namespace VTO.DAL
{
  public class Vto
  {
    public static List<DTO.VtoDto> GetVtos()
    {
      List<DTO.VtoDto> Vtos = new List<DTO.VtoDto>(3);
      Vtos.Add(new DTO.VtoDto(1010765345, "2018-03-24", "9:30:00 AM", "2:30:00 PM", 5, "Browning, Mary", "1:39:00 PM"));
      Vtos.Add(new DTO.VtoDto(1010756567, "2018-03-22", "9:30:00 AM", "12:30:00 PM", 3, "Cruz, Denise", "1:39:00 PM"));
      Vtos.Add(new DTO.VtoDto(1034534568, "2018-03-17", "8:30:00 AM", "2:30:00 PM", 6, "Perez, Breana", "1:39:00 PM"));

      return Vtos.ToList();
    }
  }
}

最后是AppModule

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';

import { AppComponent } from './components/app/app.component';
import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { HomeComponent } from './components/home/home.component';
import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
import { CounterComponent } from './components/counter/counter.component';
import { RequestProcessingComponent } from './components/request-processing/request-processing.component';
import { ContingentMaintenanceComponent } from './components/contingent-maintenance/contingent-maintenance.component';
import { TimezoneComponent } from './components/timezone/timezone.component';
import { HierarchyConfigurationComponent } from './components/hierarchy-configuration/hierarchy-configuration.component';
import { VtoReportComponent } from './components/vto-report/vto-report.component';
import { ContingentsReportComponent } from './components/contingents-report/contingents-report.component';
import { DateInputsModule } from '@progress/kendo-angular-dateinputs';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { DropDownsModule } from '@progress/kendo-angular-dropdowns';
import { JobStatusComponent } from './components/job-status/job-status.component';
import { GridModule, ExcelModule } from '@progress/kendo-angular-grid';
import { HttpClientModule, HttpClient } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent,
    NavMenuComponent,
    CounterComponent,
    FetchDataComponent,
    HomeComponent,
    RequestProcessingComponent,
    ContingentMaintenanceComponent,
    TimezoneComponent,
    HierarchyConfigurationComponent,
    VtoReportComponent,
    ContingentsReportComponent,
    JobStatusComponent
  ],
  imports: [
    CommonModule,
    HttpModule,
    HttpClientModule,
    FormsModule,
    DateInputsModule, BrowserAnimationsModule, DropDownsModule, GridModule, ExcelModule,
    RouterModule.forRoot([
      { path: '', redirectTo: 'home', pathMatch: 'full' },
      { path: 'home', component: RequestProcessingComponent },
      { path: 'counter', component: CounterComponent },
      { path: 'fetch-data', component: FetchDataComponent },
      { path: 'ContiMain', component: ContingentMaintenanceComponent },
      { path: 'HierConfig', component: HierarchyConfigurationComponent },
      { path: 'vtoreport', component: VtoReportComponent },
      { path: 'ContiReport', component: ContingentsReportComponent },

      { path: '**', redirectTo: 'home' }
    ])
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}

2 个答案:

答案 0 :(得分:5)

在AppModule中,如果您想为整个应用程序提供该服务,则需要导入Vto并将其设置为providers数组

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [],
  providers: [ Vtos ],
  bootstrap: [AppComponent]
})

或者如果您只想在该组件中使用该服务

@Component({
     ...
     providers: [ Vtos ],
 })

更多信息here

答案 1 :(得分:0)

以上答案是正确的,但就我而言,它是组件的import语句中提供的名称错误(区分大小写的问题):

import { StudentService } from '../../service/Student.service';

正确的是:

import { StudentService } from '../../service/student.service';