Angular NullInjectorError 没有服务提供者?

时间:2021-05-07 09:18:02

标签: javascript angular typescript

在我的代码中,我有一些按钮,当您单击它们时,应该会打开一个弹出窗口,您应该会以列表的形式查看详细信息。每当我单击这些按钮时,都会出现以下错误。我不知道为什么我无法到达我想要的属性。我的代码可能有什么问题,我该如何修复?

TS 代码:

@Component({
  selector: 'warehouse-detail-dialog',
  templateUrl: './warehouse-detail-dialog.component.html',
  styleUrls: ['./warehouse-detail-dialog.component.scss']
})
export class WarehouseDetailDialogComponent implements OnInit {

  cell: ICell;
  userRights: IActionRoleMap;


  displayedColumns: string[] = [
    'EntryPackageBarcode',
    'StockIntegrationCode',
    'ProductName',
    'Balance',
];
dataSource: MatTableDataSource<IStockPackageTransaction>;

@ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
@ViewChild(MatSort, { static: true }) sort: MatSort;


  /**
   *
   */
  constructor(
      private _terminalService: TerminalService,
      private _router: Router
  ) {

    _terminalService.onCellDetailChanged.subscribe((response: ICell) => {
      this.cell = response;
      

      this.dataSource = new MatTableDataSource(response.StockPackageTransactions);
      this.dataSource.paginator = this.paginator;
      this.dataSource.sort = this.sort;

  });

     
  }

服务 TS:

cellDetail: ICell;
    onCellDetailChanged: BehaviorSubject<any> = new BehaviorSubject([]);
 getCellDetailById(id: string) {
        return new Promise((resolve, reject) => {
            this._http
                .get("Production/GetCellDetailById/" + id)
                .subscribe((response: ICell) => {
                    this.cellDetail = response;
                    this.onCellDetailChanged.next(this.cellDetail);
                    resolve(this.cellDetail);
                }, reject);
        });
    }

错误:

WarehouseDetailDialogComponent_Host.ngfactory.js? [sm]:1 ERROR NullInjectorError: StaticInjectorError(AppModule)[WarehouseDetailDialogComponent -> TerminalService]: 
  StaticInjectorError(Platform: core)[WarehouseDetailDialogComponent -> TerminalService]: 
    NullInjectorError: No provider for TerminalService!
    at NullInjector.get (core.js:778)
    at resolveToken (core.js:2564)
    at tryResolveToken (core.js:2490)
    at StaticInjector.get (core.js:2353)
    at resolveToken (core.js:2564)
    at tryResolveToken (core.js:2490)
    at StaticInjector.get (core.js:2353)
    at resolveNgModuleDep (core.js:26403)
    at NgModuleRef_.get (core.js:27491)
    at resolveNgModuleDep (core.js:26403)

2 个答案:

答案 0 :(得分:3)

TerminalService 添加到相应根模块中的 providers: [] 数组(可能是 app.module.ts)。错误的线索是 No provider for TerminalService!

答案 1 :(得分:0)

在根模块的 providers 数组中提供它是一种解决方案,但您应该使用 providedIn 模式,原因有一个简单而重要的原因:摇树。如果您为您的服务提供

@Injectable({
  providedIn: 'root'
})

当你不使用它们时,它们会被摇晃并且你的包大小会更小

来源:https://angular.io/guide/providers#providedin-and-ngmodules

相关问题