为什么我在Angular应用程序中遇到此错误?未被捕获承诺:NullInjectorError

如何解决为什么我在Angular应用程序中遇到此错误?未被捕获承诺:NullInjectorError

我不太喜欢Angular和PrimeNG,并且在尝试复制此PrimeNG表展示示例时发现了以下问题(此页面的“源”选项卡中提供了代码):https://www.primefaces.org/primeng/showcase/#/table

基本上,我尝试将这段代码放入应用程序的组件中(然后将其调整到用例中)。

所以我有这个组件类:

import { Component,OnInit,ViewChild } from '@angular/core';
import { Customer,Representative } from './customer';
import { Table } from 'primeng';
import { CustomerService } from './customerservice';

@Component({
  selector: 'app-gestione-ordini',templateUrl: './gestione-ordini.component.html',styleUrls: ['./gestione-ordini.component.css']
})
export class GestioneOrdiniComponent implements OnInit {

  customers: Customer[];

  selectedCustomers: Customer[];

  representatives: Representative[];

  statuses: any[];

  loading: boolean = true;

  @ViewChild('dt') table: Table;

  constructor(private customerService: CustomerService) { }

  ngOnInit() {
    this.customerService.getCustomersLarge().then(customers => {
        this.customers = customers;
        this.loading = false;
    });

    this.representatives = [
        {name: "Amy Elsner",image: 'amyelsner.png'},{name: "Anna Fali",image: 'annafali.png'},{name: "Asiya Javayant",image: 'asiyajavayant.png'},{name: "Bernardo Dominic",image: 'bernardodominic.png'},{name: "Elwin Sharvill",image: 'elwinsharvill.png'},{name: "Ioni Bowcher",image: 'ionibowcher.png'},{name: "Ivan Magalhaes",image: 'ivanmagalhaes.png'},{name: "Onyama Limba",image: 'onyamalimba.png'},{name: "Stephen Shaw",image: 'stephenshaw.png'},{name: "XuXue Feng",image: 'xuxuefeng.png'}
    ];

    this.statuses = [
        {label: 'Unqualified',value: 'unqualified'},{label: 'Qualified',value: 'qualified'},{label: 'New',value: 'new'},{label: 'Negotiation',value: 'negotiation'},{label: 'Renewal',value: 'renewal'},{label: 'Proposal',value: 'proposal'}
    ]
  }

  onActivityChange(event) {
    const value = event.target.value;
    if (value && value.trim().length) {
        const activity = parseInt(value);

        if (!isNaN(activity)) {
            this.table.filter(activity,'activity','gte');
        }
    }
  }

  onDateSelect(value) {
      this.table.filter(this.formatDate(value),'date','equals')
  }

  formatDate(date) {
      let month = date.getMonth() + 1;
      let day = date.getDate();

      if (month < 10) {
          month = '0' + month;
      }

      if (day > 10) {
          day = '0' + day;
      }

      return date.getFullYear() + '-' + month + '-' + day;
  }

  onRepresentativeChange(event) {
      this.table.filter(event.value,'representative','in')
  }


}

这是上一组件类中使用的 CustomerService 服务:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Customer } from './customer';


@Injectable()
export class CustomerService {

    constructor(private http: HttpClient) { }

    getCustomersSmall() {
        return this.http.get<any>('assets/showcase/data/customers-small.json')
            .toPromise()
            .then(res => <Customer[]>res.data)
            .then(data => { return data; });
    }

    getCustomersMedium() {
        return this.http.get<any>('assets/showcase/data/customers-medium.json')
            .toPromise()
            .then(res => <Customer[]>res.data)
            .then(data => { return data; });
    }

    getCustomersLarge() {
        return this.http.get<any>('assets/showcase/data/customers-large.json')
            .toPromise()
            .then(res => <Customer[]>res.data)
            .then(data => { return data; });
    }

    getCustomersXLarge() {
        return this.http.get<any>('assets/showcase/data/customers-xlarge.json')
            .toPromise()
            .then(res => <Customer[]>res.data)
            .then(data => { return data; });
    }

}

这是此组件的相关html视图页面:

<div class="card">
  <p-table #dt [value]="customers" [(selection)]="selectedCustomers" dataKey="id" styleClass="p-datatable-customers" [rowHover]="true"
      [rows]="10" [showCurrentPageReport]="true" [rowsPerPageOptions]="[10,25,50]" [loading]="loading"
      [paginator]="true" currentPageReportTemplate="Showing {first} to {last} of {totalRecords} entries"
      [filterDelay]="0" [globalFilterFields]="['name','country.name','representative.name','status']">
      <ng-template pTemplate="caption">
          <div class="table-header">
              List of Cars
              <span class="p-input-icon-left">
                  <i class="pi pi-search"></i>
                  <input pInputText type="text" (input)="dt.filterGlobal($event.target.value,'contains')" placeholder="Global Search" />
              </span>
          </div>
      </ng-template>
      <ng-template pTemplate="header">
          <tr>
              <th style="width: 3rem"></th>
              <th pSortableColumn="name">Name <p-sortIcon field="name"></p-sortIcon></th>
              <th pSortableColumn="country.name">Country <p-sortIcon field="country.name"></p-sortIcon></th>
              <th pSortableColumn="representative.name">Representative <p-sortIcon field="representative.name"></p-sortIcon></th>
              <th pSortableColumn="date">Date <p-sortIcon field="date"></p-sortIcon></th>
              <th pSortableColumn="status">Status <p-sortIcon field="status"></p-sortIcon></th>
              <th pSortableColumn="activity">Activity <p-sortIcon field="activity"></p-sortIcon></th>
              <th style="width: 8rem"></th>
          </tr>
          <tr>
              <th>
                  <p-tableHeaderCheckbox></p-tableHeaderCheckbox>
              </th>
              <th>
                  <input pInputText type="text" (input)="dt.filter($event.target.value,'name','startsWith')" placeholder="Search by Name" class="p-column-filter">
              </th>
              <th>
                  <input pInputText type="text" (input)="dt.filter($event.target.value,'contains')" placeholder="Search by Country" class="p-column-filter">
              </th>
              <th>
                  <p-multiSelect [options]="representatives" placeholder="All" (onChange)="onRepresentativeChange($event)" styleClass="p-column-filter" optionLabel="name">
                      <ng-template let-option pTemplate="item">
                          <div class="p-multiselect-representative-option">
                              <img [alt]="option.label" src="assets/showcase/images/demo/avatar/{{option.value.image}}" width="32" style="vertical-align: middle" />
                              <span class="p-ml-1">{{option.label}}</span>
                          </div>
                      </ng-template>
                  </p-multiSelect>
              </th>
              <th>
                  <p-calendar (onSelect)="onDateSelect($event)" (onClearClick)="dt.filter('','equals')" [showButtonBar]="true" styleClass="p-column-filter" placeholder="Registration Date" [readonlyInput]="true" dateFormat="yy-mm-dd"></p-calendar>
              </th>
              <th>
                  <p-dropdown [options]="statuses" (onChange)="dt.filter($event.value,'status','equals')" styleClass="p-column-filter" placeholder="Select a Status" [showClear]="true">
                      <ng-template let-option pTemplate="item">
                          <span [class]="'customer-badge status-' + option.value">{{option.label}}</span>
                      </ng-template>
                  </p-dropdown>
              </th>
              <th>
                  <input pInputText type="text" (input)="onActivityChange($event)" placeholder="Minimum" class="p-column-filter" >
              </th>
              <th></th>
          </tr>
      </ng-template>
      <ng-template pTemplate="body" let-customer>
          <tr class="p-selectable-row">
              <td>
                  <p-tableCheckbox [value]="customer"></p-tableCheckbox>
              </td>
              <td>
                  <span class="p-column-title">Name</span>
                  {{customer.name}}
              </td>
              <td>
                  <span class="p-column-title">Country</span>
                  <img src="assets/showcase/images/demo/flag/flag_placeholder.png" [class]="'flag flag-' + customer.country.code" width="30">
                  <span class="image-text">{{customer.country.name}}</span>
              </td>
              <td>
                  <span class="p-column-title">Representative</span>
                  <img [alt]="customer.representative.name" src="assets/showcase/images/demo/avatar/{{customer.representative.image}}" width="32" style="vertical-align: middle" />
                  <span class="image-text">{{customer.representative.name}}</span>
              </td>
              <td>
                  <span class="p-column-title">Date</span>
                  {{customer.date}}
              </td>
              <td>
                  <span class="p-column-title">Status</span>
                  <span [class]="'customer-badge status-' + customer.status">{{customer.status}}</span>
              </td>
              <td>
                  <span class="p-column-title">Activity</span>
                  <p-progressBar [value]="customer.activity" [showValue]="false"></p-progressBar>
              </td>
              <td style="text-align: center">
                  <button pButton type="button" class="p-button-secondary" icon="pi pi-cog"></button>
              </td>
          </tr>
      </ng-template>
      <ng-template pTemplate="emptymessage">
          <tr>
              <td colspan="8">No customers found.</td>
          </tr>
      </ng-template>
  </p-table>
</div>

它可以正确编译,但是问题是,当我运行我的应用程序而不是获取期望的表时,我正在获取此错误消息:

core.js:6228 ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[CustomerService -> CustomerService -> CustomerService]: 
  NullInjectorError: No provider for CustomerService!
NullInjectorError: R3InjectorError(AppModule)[CustomerService -> CustomerService -> CustomerService]: 
  NullInjectorError: No provider for CustomerService!
    at NullInjector.get (core.js:1085)
    at R3Injector.get (core.js:16955)
    at R3Injector.get (core.js:16955)
    at R3Injector.get (core.js:16955)
    at NgModuleRef$1.get (core.js:36329)
    at Object.get (core.js:33972)
    at getOrCreateInjectable (core.js:5848)
    at Module.ɵɵdirectiveInject (core.js:21103)
    at NodeInjectorFactory.GestioneOrdiniComponent_Factory [as factory] (gestione-ordini.component.ts:11)
    at getNodeInjectable (core.js:5993)
    at resolvePromise (zone-evergreen.js:798)
    at resolvePromise (zone-evergreen.js:750)
    at zone-evergreen.js:860
    at ZoneDelegate.invokeTask (zone-evergreen.js:399)
    at Object.onInvokeTask (core.js:41632)
    at ZoneDelegate.invokeTask (zone-evergreen.js:398)
    at Zone.runTask (zone-evergreen.js:167)
    at drainMicroTaskQueue (zone-evergreen.js:569)

为什么会出现此错误?可能是什么问题?

解决方法

尝试添加

@Injectable({provided in: "root"})

到您的服务班级。这会将其包括在根注入器中,并使它可用于您应用程序中的任何实体。

或者,如果仅希望将此服务提供给部分应用程序,则需要将其包含在Provides数组的NgModule中

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-