我有 2 个用 Ionic 和 Angular 19 编写的项目,它们在生产环境中而不是在开发版本中给出 Nullinjector 错误。为了找出导致这些问题的原因,我将我的一个项目精简到最低限度,但仍然收到这些 Nullinjector 错误。我无法获得更多信息,例如不正确的提供程序,因为 Nullinjector 错误不会提供生产中的更多详细信息。错误示例:
NullInjectorError: R3InjectorError[t -> _i -> _i]:
NullInjectorError: No provider for _i!
最小的
app.config.ts
看起来像这样:
import { ApplicationConfig, importProvidersFrom } from '@angular/core';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { RouteReuseStrategy } from '@angular/router';
import { provideRouter, withPreloading, PreloadAllModules } from '@angular/router';
import { routes } from './app-routing.module';
import { provideAuth, getAuth, indexedDBLocalPersistence, browserLocalPersistence } from '@angular/fire/auth';
import { isPlatform } from '@ionic/angular';
export const appConfig: ApplicationConfig = {
providers: [
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
provideAuth(() => {
const auth = getAuth();
if (isPlatform('android')) {
auth.setPersistence(indexedDBLocalPersistence);
} else {
auth.setPersistence(browserLocalPersistence);
}
return auth;
}),
provideRouter(routes, withPreloading(PreloadAllModules)),
importProvidersFrom(IonicModule.forRoot())
]
};
这里可能缺少什么?
您可以直接使用核心 Firebase SDK 来初始化和使用 Firebase 服务,而不是使用
@angular/fire
。具体方法如下:
运行以下命令来安装 Firebase Core SDK:
npm i firebase
首先,设置 Firebase 服务来处理初始化:
import { Platform } from '@ionic/angular';
import { Injectable } from '@angular/core';
import { FirebaseApp, initializeApp } from 'firebase/app';
import { Auth, getAuth, initializeAuth, indexedDBLocalPersistence } from 'firebase/auth';
@Injectable({ providedIn: 'root' })
export class FirebaseService {
firebaseAuth!: Auth;
constructor(private readonly platform: Platform) {}
private firebaseAuthInitialization(app: FirebaseApp): Auth {
if (this.platform.is('capacitor')) {
// use IndexedDB persistence for native platforms
return initializeAuth(app, { persistence: indexedDBLocalPersistence });
} else {
// use default persistence for web platforms
return getAuth(app);
}
}
public async initializeApp(): Promise<void> {
const app = initializeApp(environment.firebaseConfig);
this.firebaseAuth = this.firebaseAuthInitialization(app);
}
}
然后,在应用程序组件文件中调用firebase服务。
import { Component } from '@angular/core';
import { FirebaseService } from './services/firebase.service';
@Component({
standalone: true,
selector: 'app-root',
templateUrl: 'app.component.html',
})
export class AppComponent {
constructor(private readonly firebaseService: FirebaseService) {
this.firebaseService.initializeApp();
}
}