AngularDart集成Firestore报错:firebase.firestore is not a function
Hey there! Let's work through that firebase.firestore is not a function error you're hitting with your Angular Dart Firebase service. This issue usually pops up when the Firestore JavaScript SDK isn't properly loaded or your Dart code isn't initializing Firestore correctly. Here's how to fix it step by step:
For web-based Angular Dart projects, you need to include the Firestore-specific SDK script in your web/index.html file. If you only have the base Firebase app script, Firestore won't be available. Add these scripts right before the closing </body> tag:
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script> <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-firestore.js"></script>
Pro tip: Use a SDK version that matches the compatibility of your Dart firebase package to avoid version mismatch issues.
Right now, you're setting up the Firebase app but not explicitly grabbing the Firestore instance. This can lead to the module not being ready when you try to use DocumentReference. Update your service like this:
import 'package:firebase/firebase.dart' as fb; import 'package:firebase/firestore.dart' as fs; import 'dart:async'; import 'package:angular/angular.dart'; @Injectable() class FirebaseService { fb.User user; fs.Firestore firestore; // Add a Firestore instance variable fs.DocumentReference reference; FirebaseService() { fb.initializeApp( apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx", authDomain: "xxxxxx.firebaseapp.com", databaseURL: "https://xxxxxx.firebaseio.com", projectId: "xxxxxxx", storageBucket: "xxxxxxx.appspot.com" // Fill in your storage bucket value ); // Explicitly get the Firestore instance after initializing the app firestore = fb.firestore(); } }
This ensures Firestore is fully initialized before you try to use any of its features like DocumentReference.
Check your pubspec.yaml to make sure you're using a stable, supported version of the firebase package that includes Firestore support. For example:
dependencies: firebase: ^9.0.0 angular: ^6.0.0
Run pub get after updating to pull in the correct dependencies.
In Angular Dart, service constructors can run before the browser has fully loaded the Firebase SDK. If you're trying to use Firestore right away in a component, wait until the component's ngOnInit lifecycle hook to call your Firebase service methods:
@Component( selector: 'your-component', template: '...', ) class YourComponent implements OnInit { final FirebaseService fbService; YourComponent(this.fbService); @override void ngOnInit() { // Now it's safe to interact with Firestore var usersCollection = fbService.firestore.collection('users'); // Do your Firestore operations here } }
If you still run into issues, check your browser's developer console for additional error messages—they might hint at other problems like invalid API keys or network issues preventing the SDK from loading.
内容的提问来源于stack exchange,提问作者alf

