StaticInjectorError (AppModule) [AppComponent -> DataService] - PullRequest
0 голосов
/ 09 ноября 2019

Я следовал инструкциям по настройке среднего стека, но при запуске моего кода на локальном хосте я получаю пустой экран с ошибкой «StaticInjectorError (AppModule) [DataService -> Http]:». Я потратил два дня, пытаясь выяснить эту ошибку, и ничего не смог найти.

Что касается деталей об используемых мной инструментах, Angular 8.3.17, узел v12

data.service.ts

import { Injectable } from '@angular/core';

import { Http, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';


@Injectable()
export class DataService {

  result:any;

  constructor(private _http: Http) { }

  getAccounts() {
    return this._http.get("/api/accounts")
      .map(result => this.result = result.json().data);
  }

}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

// Import the Http Module and our Data Service
import { HttpModule } from '@angular/http';
import { DataService } from './data.service';

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

app.component.ts

import { Component } from '@angular/core';

// Import the DataService
import { DataService } from './data.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  // Define a users property to hold our user data
  accounts: Array<any>;

  // Create an instance of the DataService through dependency injection
  constructor(private _dataService: DataService) {

    // Access the Data Service's getUsers() method we defined
    this._dataService.getAccounts()
        .subscribe(res => this.accounts = res);
  }
}

Ответы [ 2 ]

0 голосов
/ 09 ноября 2019

Вам необходимо добавить DataService в часть провайдеров файла app.module.ts, как этот

providers: [DataService],
0 голосов
/ 09 ноября 2019

Я обнаружил проблему, мне пришлось добавить dataService в мой массив провайдеров и HttpModule для импорта.

  @NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpModule,
    AppRoutingModule
  ],
  providers: [DataService],
  bootstrap: [AppComponent]
})
...