StaticInjectorError AppModule UsersListComponent-> UsersListService角度5

时间:2018-08-24 03:23:48

标签: angular angular-material

我正在练习如何将数据绑定到Angular Material Datatables,并且在绑定数据时在控制台中遇到此错误。我搜索了很多论坛,但找不到解决问题的答案,因此请花点时间清除我的错误。谢谢。

模型

export interface User {
    name: string;
}

服务

import { Injectable } from '@angular/core';
import { User } from '../_models/userModel';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class UsersListService {
    private url = 'http://localhost:3000/api/users';

constructor(public http: HttpClient) { }

    getUser():Observable<User[]> {
        return this.http.get<User[]>(this.url);
    }
}

组件

import { UsersListService } from './../_services/usersList.service';
import { Observable } from 'rxjs/Observable';
import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import { MatTableDataSource, MatSort, MatSortable } from "@angular/material";

@Component({
  selector: 'app-usersList',
  templateUrl: './usersList.component.html',
  styleUrls: ['./usersList.component.css']
})
export class UsersListComponent implements OnInit {
  usersList = [];
  displayedColumns= ["name"];
  dataSource;

  constructor(private UsersListService:UsersListService) {
    /* this.usersData(); */
   }

  ngOnInit() {
    this.UsersListService.getUser().subscribe( results => {
      if(!results) {
        return;
      }
      this.dataSource = new MatTableDataSource(results);
    });
  }

HTML

<mat-table [dataSource]="dataSource" class="mat-elevation-z8">
  <!-- Name Column -->
  <ng-container matColumnDef="name">
    <mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element.name}} </mat-cell>
  </ng-container>

  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>

错误

ERROR Error: StaticInjectorError(AppModule)[UsersListComponent -> UsersListService]: 
  StaticInjectorError(Platform: core)[UsersListComponent -> UsersListService]: 
    NullInjectorError: No provider for UsersListService!
    at _NullInjector.get (core.js:1003)
    at resolveToken (core.js:1301)
    at tryResolveToken (core.js:1243)
    at StaticInjector.get (core.js:1111)
    at resolveToken (core.js:1301)
    at tryResolveToken (core.js:1243)
    at StaticInjector.get (core.js:1111)
    at resolveNgModuleDep (core.js:10896)
    at NgModuleRef_.get (core.js:12129)
    at resolveDep (core.js:12619)

1 个答案:

答案 0 :(得分:1)

您需要在提供者部分中将服务添加到app.module中

import { YourService } from "./the_location_of_your_service";
.
.
.

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