Ionic 3集成Angularfire2报错:找不到angularfire2/database模块
你在Ionic 3项目中尝试连接Firebase数据库时遇到了模块找不到的错误,不管导入angularfire2/database还是angularfire2/database-deprecated都没法解决,我来帮你一步步排查:
首先看你提供的app.module.ts代码:
import { BrowserModule } from '@angular/platform-browser'; import { ErrorHandler, NgModule } from '@angular/core'; import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular'; import { SplashScreen } from '@ionic-native/splash-screen'; import { StatusBar } from '@ionic-native/status-bar'; import { AngularFireDatabase, AngularFireDatabaseModule } from 'angularfire2/database'; import { AngularFireModule } from 'angularfire2'; import { environment } from '../environments/environment'; import { MyApp } from './app.component'; import { HomePage } from '../pages/home/home'; @NgModule({ declarations: [ MyApp, HomePage ], imports: [ BrowserModule, IonicModule.forRoot(MyApp), AngularFireModule.initializeApp(environment.firebase), AngularFireDatabaseModule ], bootstrap: [IonicApp], entryComponents: [ MyApp, HomePage ], providers: [ AngularFireDatabase, StatusBar, SplashScreen, {provide: ErrorHandler, useClass: IonicErrorHandler} ] }) export class AppModule {}
你提到的报错导入语句:
import { AngularFireDatabase, AngularFireDatabaseModule } from 'angularfire2/database';
运行时错误信息:
Runtime Error Cannot find module "angularfire2/database"
Stack
Error: Cannot find module "angularfire2/database"
at Object.217 (http://localhost:8100/build/main.js:78:7)
at webpack_require (http://localhost:8100/build/vendor.js:55:30)
at Object.194 (http://localhost:8100/build/main.js:60:70)
at webpack_require (http://localhost:8100/build/vendor.js:55:30)
at webpackJsonpCallback (http://localhost:8100/build/vendor.js:26:23)
at http://localhost:8100/build/main.js:1:1
问题根源与解决方案
这个问题主要是AngularFire2版本和Ionic 3的兼容性问题,因为Ionic 3对应的是Angular 5.x,而新版本的AngularFire2(比如6.x+)只支持Angular 6+,所以会出现模块找不到的情况。
你可以按照以下步骤解决:
安装兼容的AngularFire2版本
卸载当前的angularfire2和firebase,重新安装适合Ionic3的版本:npm uninstall angularfire2 firebase --save npm install angularfire2@5.0.0-rc.6 firebase@4.8.0 --save这个版本组合是经过验证可以和Ionic 3完美配合的。
确认导入路径正确
对于这个版本,正确的数据库模块导入路径就是angularfire2/database,不需要用database-deprecated,所以你原来的导入语句是对的,只要版本装对就不会报错。检查environment.ts配置
确保src/environments/environment.ts里的Firebase配置信息正确无误:export const environment = { production: false, firebase: { apiKey: "你的apiKey", authDomain: "你的authDomain", databaseURL: "你的databaseURL", projectId: "你的projectId", storageBucket: "你的storageBucket", messagingSenderId: "你的messagingSenderId" } };重新构建项目
安装完依赖后,清理缓存并重新构建:ionic cordova clean ionic serve
这样应该就能解决模块找不到的问题了,试试上面的步骤吧!
内容的提问来源于stack exchange,提问作者Biswajit

