Angular 5,NullInjectorError:没有服务提供者

Mr.*_*ast 9 typescript angular google-cloud-firestore angular5

您好我试图在我的Web应用程序中实现firestore,当我向构造函数添加服务时出现错误:

NullInjectorError:没有TesteventService的提供者!

我正在使用Angular 5,angularfire2/firestore和typescript 2.7.1

testevent.service.ts

import { Injectable } from '@angular/core';
import { AngularFirestore } from 'angularfire2/firestore'

@Injectable()
export class TesteventService {

  constructor(private afs: AngularFirestore) { }

  addEvent(eventData){
    this.afs.collection('testevent').add(eventData).then(() => {
      console.log('Done');
    })
  }

  getEvent(){
    return this.afs.collection('testevent', ref => ref.orderBy('id')).valueChanges()
  }
}
Run Code Online (Sandbox Code Playgroud)

component.ts

import { Component, OnInit } from '@angular/core';
import { TesteventService } from '../../providers/testevent.service';
import { AngularFirestore } from 'angularfire2/firestore';

export class CsvImportComponent implements OnInit {
  data_rows = []

  constructor(private event: TesteventService){})
Run Code Online (Sandbox Code Playgroud)

当我从TesteventSerivice添加事件时,我得到错误,而没有任何运行.

小智 27

使用 - 注释您的服务类

@Injectable({ providedIn: 'root' })
Run Code Online (Sandbox Code Playgroud)

服务本身是 CLI 生成的一个类,它用@Injectable(). 默认情况下,这个装饰器有一个providedIn属性,它为服务创建一个提供者。在这种情况下,providedIn: 'root'指定 Angular 应该在根注入器中提供服务。

  • 你能在你的代码中添加一些解释吗?为什么要这样做? (4认同)

Saj*_*ran 25

您需要在app.module.ts中的导入下的提供程序下添加TesteventService

providers: [
  TesteventService 
]
Run Code Online (Sandbox Code Playgroud)


Sho*_*lil 12

解决这个问题有两种可能:

  1. 您可以像这样在 app.module.ts 提供程序数组中提供您的服务名称,错误将会消失:
imports: [
],

declarations: [
],

providers: [  TesteventService ]
Run Code Online (Sandbox Code Playgroud)
  1. 对于某些最新版本的 Angular,您可以这样简单地注释您所需的服务:
@Injectable({ providedIn: 'root' })
Run Code Online (Sandbox Code Playgroud)