4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

AngularFire - NullInjectorErrorの対処法

Posted at

AngularFire を操作する中で、少しハマった部分があったので、備忘録として残しておきます。

事象

AngularFire の AngularFireDatabase モジュールを利用して、Realtime Database に接続しようとした際に以下のエラーが発生しました。
No provider for InjectionToken とのことなので、providers に AngularFireDatabase をセットすればいいようだがイマイチうまくいかず。。

ERROR NullInjectorError: R3InjectorError(AppModule)[AngularFireDatabase -> InjectionToken angularfire2.app.options -> InjectionToken angularfire2.app.options -> InjectionToken angularfire2.app.options]: 
  NullInjectorError: No provider for InjectionToken angularfire2.app.options!

環境

ng version での出力結果。
@angular/fire の7系が関連している模様。

@angular-devkit/architect       0.1302.6
@angular-devkit/build-angular   13.2.6
@angular-devkit/core            13.2.6
@angular-devkit/schematics      13.2.6
@angular/cli                    13.2.6
@angular/fire                   7.3.0
@schematics/angular             13.2.6
rxjs                            7.5.5

対処策

providersがセットされていないとのエラーでしたが、その中の書き方を少し工夫しないとダメでした。

app.module.ts
import { NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms";
import { BrowserModule } from "@angular/platform-browser";

import { AppComponent } from "./app.component";
import { CommentDatePipe } from "./pipes/comment-date.pipe";
import { initializeApp, provideFirebaseApp } from "@angular/fire/app";
import { environment } from "../environments/environment";
import { provideAuth, getAuth } from "@angular/fire/auth";
import { provideDatabase, getDatabase } from "@angular/fire/database";
import { FIREBASE_OPTIONS } from "@angular/fire/compat";

@NgModule({
  declarations: [AppComponent, CommentDatePipe],
  imports: [
    BrowserModule,
    FormsModule,
    provideFirebaseApp(() => initializeApp(environment.firebase)),
    provideAuth(() => getAuth()),
    provideDatabase(() => getDatabase()),
  ],
  providers: [{ provide: FIREBASE_OPTIONS, useValue: environment.firebase }],
  bootstrap: [AppComponent],
})
export class AppModule {}

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?