ERROR NullInjectorError: R3InjectorError(AppModule)
Asked Answered
R

11

41

I am trying to save the value from my component to firebase using service. But I am getting NullInjector Error when ever I use service. I did everything that was not the internet. Imported everything but it wont work. I already tried importing HttpClientModule, AngularFireDatabase but nothing works. I have tried to completely recreate the project by freshly installing everything. I have tried different versions of firebase and angular (currently [email protected] @angular/[email protected]). Nothing works.

This is my fireservice.service

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';

@Injectable({
  providedIn: 'root'
})
export class FireserviceService {

  constructor(private db: AngularFireDatabase) {
    
   }
   create(){
    return this.db.list('/shopping-carts').push({
      dateCreated:new Date().getTime()
    });
  }
}

this is my app module

import { FireserviceService } from './fireservice.service';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { environment } from '../environments/environment';
import { AngularFirestore } from '@angular/fire/firestore';
import { AngularFireModule } from '@angular/fire';
import { AngularFirestoreModule } from '@angular/fire/firestore';
import { BrainComponent } from './brain/brain.component';


@NgModule({
  declarations: [
    AppComponent,
    BrainComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFirestoreModule
  ],
  providers: [
    AngularFirestore,
    FireserviceService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { 
  constructor(){

  }
}

this is my compnent

import { FireserviceService } from './../fireservice.service';
import { Component, OnInit } from '@angular/core';


@Component({
  selector: 'brain',
  templateUrl: './brain.component.html',
  styleUrls: ['./brain.component.css']
})
export class BrainComponent  {

  constructor(private cartService: FireserviceService) { }
  addToCart(val:any){
    console.log(val)
  }

}

This is the error I get

core.js:6142 ERROR NullInjectorError: R3InjectorError(AppModule)[FireserviceService -> AngularFireDatabase -> AngularFireDatabase -> AngularFireDatabase]: 
  NullInjectorError: No provider for AngularFireDatabase!
    at NullInjector.get (http://localhost:51081/vendor.js:38768:27)
    at R3Injector.get (http://localhost:51081/vendor.js:38935:33)
    at R3Injector.get (http://localhost:51081/vendor.js:38935:33)
    at R3Injector.get (http://localhost:51081/vendor.js:38935:33)
    at injectInjectorOnly (http://localhost:51081/vendor.js:32465:33)
    at Module.ɵɵinject (http://localhost:51081/vendor.js:32469:61)
    at Object.FireserviceService_Factory [as factory] (http://localhost:51081/main.js:280:159)
    at R3Injector.hydrate (http://localhost:51081/vendor.js:39103:35)
    at R3Injector.get (http://localhost:51081/vendor.js:38924:33)
    at NgModuleRef$1.get (http://localhost:51081/vendor.js:53004:33)

The site works fine until I add parameters to the constructor in the brain component. But as soon as I add private cartService: FireserviceService in the constructor in the brain component it won't even load HTML. I am new to angular and firebase. I am trying to save the value in the firebase database. Please help.

Radium answered 18/2, 2021 at 1:32 Comment(1)
Thanks for your question. If others are like me, they may see this error with obfuscated service names, so it's hard to understand NullInjectorError: R3InjectorError(Standalone[_a14])[_a12 -> _a12 -> _a11 -> _a11]: I don't know why the error message is obfuscated like that but my solution was as suggested in this answer, that is to make sure all my services (and the services needed by the original services, etc...) use the @Injectable({ providedIn: 'root' }) syntaxMainly
F
29

You can see from the error message that the dependency container is missing a provider for AngularFireDatabase:

" No provider for AngularFireDatabase"

If you use AngularFireDatabase you need to import that service in app.module.ts in providers - you're currently importing AngularFirestore.

  providers: [
    AngularFireDatabase,
    FireserviceService
  ],
Fumy answered 23/2, 2021 at 9:22 Comment(1)
The answer states it needed to provide AngularFireDatabase, not AngularFirestore, which indeed was imported. So it was indeed helpful.Pix
V
25

Check in your service whether @Injectable annotation is as shown below:

@Injectable({
  providedIn: 'root'
})
Vendace answered 20/8, 2021 at 14:47 Comment(1)
And if you don't want the service to be provided by the root module?Embark
C
20

Import HttpClientModule into app.module.ts and add HttpClientModule to imports array.

import { HttpClientModule } from '@angular/common/http';

 imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
Cl answered 9/7, 2021 at 5:40 Comment(0)
V
3

This is because you are trying to use Angular Fire Database but imported Angular Firestore Module and Angular Firestore in app module.

Replace AngularFirestoreModule with AngularFireDatabaseModule and AngularFirestore with AngularFireDatabase in app.module.ts

  imports: [
    BrowserModule,
    AppRoutingModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireDatabaseModule
  ],
  providers: [
    AngularFireDatabase,
    FireserviceService
  ],

However, I will recommend to use Angular Firestore instead of Angular Fire Database if you are starting new.

https://github.com/angular/angularfire/blob/master/docs/install-and-setup.md

Volant answered 18/2, 2021 at 5:41 Comment(2)
Thank you so much. After I followed your instruction it gave me an error saying "Error: ./src/app/app.module.factory.js 19:2850-2872 "export 'RealtimeDatabaseURL' (imported as 'i8') was not found in '@angular/fire'". I look through the internet a bit and found out I had to change the versions of angular and angular fire to a compatible one. I changed angular to 9 and angular fire to 5.4.2. It is working now.Radium
I tried to replicate a similar code to my main project and now it is not working again. It is giving me the same error.Radium
C
1

This thread may help,

If you are using libraries and add firebase as dependency, you have to keep both place with the same version

Meaning if

MainApp

"dependencies": { 
  "@my/lib": "1.0.0",
  "firebase": "7.22.0" 
}

@my/lib

"dependencies": { 
  "firebase": "7.24.0"  // <-- The version is higher
}

Then you will face the same error. The way to fix this would be to bump the @another/lib version into MainApp from 7.22.0 to 7.24.0.

See the linked issue to see why you shouldn't import it into the dependencies but into the peerDependencies

Cali answered 7/1, 2022 at 14:18 Comment(0)
H
1

I Has same issue. I fixed this by changing from

import { Database, onValue, ref, set } from "firebase/database";

to

import { Database, onValue, ref, set } from "@angular/fire/database";

in service. (Angular 13 & Fire 7.3.0)

Hydrogeology answered 1/4, 2022 at 22:8 Comment(0)
Z
1

you should check if yo have imported the HttpClientModule since services usually uses it and I didn't see it in your code. Try it and give me some feedback! I had this same problem and I did solve it by importing the HttpClientModule

I have imported it in app.module like this

import { HttpClientModule } from '@angular/common/http'; // HERE

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    ...
    HttpClientModule // HERE
    ...
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

and also you should check if you have de @Injectable decorator with the providedIn: 'root' in the service class like this

@Injectable({
  providedIn: 'root' // HERE
})
export class SocialPostsService {
Zymase answered 23/1, 2023 at 2:32 Comment(0)
L
1

if you are facing this error in angular 17 version just remove all HTTP client module imports and go to appconfig.ts file inside app file

import { provideHttpClient } from '@angular/common/http';

export const appConfig: ApplicationConfig = {
  providers: [provideRouter(routes), provideHttpClient()],
};

restart your application

Leaven answered 22/2 at 6:49 Comment(0)
G
0

This should work for you :

In your app.module.ts > imports:[ ]

Replace this :

provideFirebaseApp(() => initializeApp(environment.firebase)),
provideFirestore(() => getFirestore())

with this :

AngularFireModule.initializeApp(environment.firebase),
AngularFireDatabaseModule
Gazehound answered 16/12, 2021 at 18:48 Comment(0)
I
0

In main.ts

import { ApplicationConfig, importProvidersFrom } from '@angular/core';
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';
import { HttpClientModule } from '@angular/common/http';

export const appConfig: ApplicationConfig = 
{ providers [provideRouter(routes), importProvidersFrom(HttpClientModule)]};
Instigation answered 17/1 at 4:39 Comment(0)
S
0

My issue was missing this

import { initializeApp, provideFirebaseApp } from '@angular/fire/app';

@NgModule({
imports: [
  ...
  provideFirebaseApp(() => initializeApp(environment.firebaseConfig)),
  ...
],

in app.module.ts

Smokedry answered 22/3 at 20:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.