AngularFire#7.1.1: NullInjectorError: No provider for Firestore - firebase

I'm getting the following error message with my Angular 12 app: NullInjectorError: No provider for Firestore!
Firestore is initialized both the old and the new way in my lazy loaded admin.module.ts
import { connectFirestoreEmulator, getFirestore, provideFirestore } from "#angular/fire/firestore";
import { AngularFirestoreModule } from "#angular/fire/compat/firestore";
...
imports: [
AngularFirestoreModule,
provideFirestore(() => {
const firestore = getFirestore();
if (!environment.production) {
connectFirestoreEmulator(firestore, "localhost", 8080);
}
return firestore;
}),
]
Also setting up Firebase both ways in my app.module.ts
import { provideFirebaseApp, initializeApp } from "#angular/fire/app";
import { AngularFireModule } from "#angular/fire/compat";
...
imports: [
AngularFireModule.initializeApp(environment.firebase),
provideFirebaseApp(() => initializeApp(environment.firebase)),
]
And finally, using Firestore in one of my services, (let's call it foo.service.ts) that is being provided by my admin.module.ts
import { Firestore } from "#angular/fire/firestore";
...
export class ScanRepositoryService {
constructor(private firestore: Firestore) {}
}
From what I can tell, I'm following the AngularFire documentation pretty strictly, still, getting this error message about my service can't resolve Firestore. Re-installing the whole node_modules and re-compiling the app with both dev and production flags did not help. Any other idea how to solve this issue?

Solved by removing all the "old" non-modular usage of Firestore, leaving only the version 9+ parts.

Related

Module '"#angular/fire"' has no member 'AngularFireModule' exported [duplicate]

I am very new to firebase firestore.
And this is my first project with firestore.
I installed angular fire with this command
npm install firebase #angular/fire --save
and now importing the angularfiremodule like this
import { AngularFireModule } from '#angular/fire';
and angularfirestoremodule like this
import { AngularFirestoreModule } from '#angular/fire/firestore';
But this is giving me error
Cannot find module '#angular/fire'.ts(2307)
Any idea what might be the error?
I tried google searching but since I am new to firebase, everything seems very mixed up to me.
Also, I'm using ionic version 4, Angular version 8.1.3 and node version 10.16.3 if that makes any difference.
Angularfire2 was working fine previously, but since it's deprecated, I want to move to angular/fire.
I solved the problem by using below import statement, in app.module.ts
import { AngularFirestoreModule } from '#angular/fire/compat/firestore/';
My problem solved by using import like this which i have mentioned below with firebase version 9 and firestore 7 and angular 12.
As per the offical document
Documentation
Got reference from this link:
https://dev.to/jdgamble555/angular-12-with-firebase-9-49a0
For official reference check this out:
https://firebase.google.com/docs/firestore/quickstart
Install firestore by using
ng add #angular/fire
Install firebase by using
npm install firebase
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { provideFirebaseApp, initializeApp } from '#angular/fire/app';
import { getAuth, provideAuth } from '#angular/fire/auth';
import { getFirestore, provideFirestore } from '#angular/fire/firestore';
import { getStorage, provideStorage } from '#angular/fire/storage';
import { getAnalytics, provideAnalytics } from '#angular/fire/analytics';
import { environment } from '../environments/environment';
#NgModule({
declarations: [
AppComponent,
DashboardComponent,
ForgotPasswordComponent,
SignInComponent,
SignUpComponent,
VerifyEmailComponent
],
imports: [
provideFirebaseApp(() => initializeApp(environment.firebaseConfig)),
provideFirestore(() => getFirestore()),
provideAuth(() => getAuth()),
provideStorage(() => getStorage()),
provideAnalytics(() => getAnalytics()),
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
There's some version mismatch issue here.
Here's what you might want to do in order to make this work.
DISCLAIMER: I'll be using StackBlitz for Demo Purposes.
Steps to follow:
Navigate to the StackBlitz Template Link mentioned in the Quick Links section of #angular/fire GitHub README.
Try importing AngularFirestoreModule in the AppModule and add it to the imports array.
import { AngularFirestoreModule } from '#angular/fire/firestore';
Go to your AppComponent and import AngularFirestore and inject it as a dependency:
import { Component } from '#angular/core';
import { Observable } from 'rxjs';
import { AngularFirestore } from '#angular/fire/firestore';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
items: Observable<any[]>;
constructor(db: AngularFirestore) {
this.items = db.collection('items').valueChanges();
}
}
You'll get an error saying:
ERROR Error: app.firestore is not a function
You would like to do a Google search finding the reason and a probable fix for the issue. You'll probably end up on this GitHub thread which would suggest that you reinstall the dependencies.
Since we are on StackBlitz, you'll just press the "Update all deps to latest" button in the DEPENDENCIES section. As soon as you do that, you'll start getting an error saying:
Can't find package:core-js
It's apparently a known issue for StackBlitz. In order to fix it, you'll do a Google search again and probably end up on this GitHub thread.
As suggested in the thread, you'll install core-js#2 by adding it to the DEPENDENCIES Field and pressing enter. This will install Version 2.6.11 of core-js.
Now you'll get an error saying:
Can't find package:#firebase/app
To fix it, you'll just click on the blue button that says "INSTALL PACKAGE #firebase/app"
Finally, you'll get an error saying:
ERROR Error: "projectId" not provided in firebase.initializeApp.
To fix this, just paste in your firebase config.
And hopefully, after following all these steps, you should be able to see the project updated to #angular/fire.
Here's a Working Demo till Step 9 to save some of your time.
Hope this helps :)
In app.module.ts add this
import { AngularFirestoreModule } from '#angular/fire/firestore';
In your file import AngularFireStore as
import { AngularFirestore, AngularFirestoreCollection } from '#angular/fire/compat/firestore';

Identifier 'module' has already been declared - amplify and nuxt 3

I am getting an error in nuxt3 then setting up this amplify plugin. I am trying to add auth to nuxt3 via plugins
plugins/amplify.js
import Amplify, {withSSRContext} from 'aws-amplify';
export default defineNuxtPlugin((ctx) => {
const awsConfig = {
Auth: {
region: "ap-south-1",
userPoolId: "ap-south-1_#########",
userPoolWebClientId: "#####################",
authenticationFlowType: "USER_SRP_AUTH",
},
};
Amplify.configure({ ...awsConfig, ssr: true });
if (process.server) {
const { Auth } = withSSRContext(ctx.req);
return {
provide: {
auth: Auth,
},
};
}
return {
provide: {
auth: Auth,
},
};
}
[nuxt] [request error] Identifier 'module' has already been declared
at Loader.moduleStrategy (internal/modules/esm/translators.js:145:18)
at async link (internal/modules/esm/module_job.js:67:21)
Does anyone know what's going on?
Been facing this myself... I don't think its a nuxt problem but rather Vite.
I gave up on running the app on dev mode and just resorted to building the app and launching it. Also, in order to use aws-amplify with vite you need to apply some workarounds:
https://ui.docs.amplify.aws/vue/getting-started/troubleshooting
For the window statement (which only makes sense on the browser) you'll need to wrap that with an if statement. Added this to my plugin file
if (process.client) {
window.global = window;
var exports = {};
}
This will let you build the project and run it with npm run build . Far from ideal but unless someone knows how to fix that issue with dev in vite...
BTW, you can also just switch to webpack builder on nuxt settings and the issue goes away.
// https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({
builder: "webpack"
});
I think this might be a problem with auto imports of nuxt.
I added a ~/composables/useBucket.ts file which I used in ~/api. Same error started popping up the next day. After I moved ~/composables/useBucket.ts to ~/composablesServer/useBucket.ts issue disappeared.

firebase.firestore.GeoPoint(long, lat) is not a constructor

I need your help...
I am unable to save an object with geodata to my firestore (from a vue application).
Objects without a geopoint are saved to firestore, but as soon as I try to add a document with the GeoPoint Class, I get the following error:
Uncaught TypeError: this.$db.GeoPoint is not a constructor
at VueComponent.addProperty (index.2ad219460d4ddfd5635c.hot-update.js:226)
at click (index.3901b064c6620cd7292b.hot-update.js:149)
at invoker (commons.app.js:10574)
at HTMLButtonElement.fn._withTask.fn._withTask [...]
'This.$db' is a reference to the firebase.firestore() object -> since it works without GeoPoints this import/injection should be correct (I also tried it with the direct import of the firebase-instance without success.
My function looks as follows:
this.$db.collection("property").add({
meta_data:this.meta_data,
address: this.address,
location: new this.$db.GeoPoint(8.241, 46.838)
})
.then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
My dependencies:
"dependencies": {
"#mapbox/mapbox-gl-geocoder": "^2.3.0",
"#mapbox/mapbox-sdk": "^0.4.1",
"firebase": "^5.5.3",
"geojson": "^0.5.0",
"gsap": "^2.0.2",
"mapbox-gl": "^0.49.0",
"nuxt": "^2.1.0",
"vuefire": "^1.4.5",
"vuetify": "^1.2.9"
},
Do I miss something? Any help is appreciated! Thanks a lot
I found the root cause of my problem. My firestore import was incorrect.
This.$db # -> was a reference to firebase.firestore()
What it should be instead
This.$db # -> should be a reference to firebase.firestore (without parentheses())
therefore the constructor was not available.
I have a not pretty solution. I recall the firebase module and use the functionality raw. Just in my own componente.
<script>
import firebase from 'firebase/app'
import 'firebase/storage'
export default {
beforeMount() {
const geopoint = firebase.firestore
console.log(new geopoint.GeoPoint(-0.180653, -78.467834))
},
}
</script>
I have the same error in my vue application, I referred to external firebase file when I was creating geopoint, the solution in my case was adding:
import { firebase } from '#firebase/app';

Detected an object of type "Timestamp" that doesn't match the expected instance

I'm wondering why is the Timestamp object is not working as I expect?
It works in test environment (I use Mocha), but throws error when it has been deployed.
index.ts
import { Timestamp, QuerySnapshot } from "#google-cloud/firestore";
....
async someFunction() {
let col = firestore.collection("mycollection");
let now = Timestamp.now();
let twentyMinsAgo = Timestamp.fromMillis(now.toMillis() - (1200 * 1000));
return col
.where('LastEdited', '>=', twentyMinsAgo) //This throws error
.get()
}
Stack Trace
Argument "value" is not a valid QueryValue.
Detected an object of type "Timestamp" that doesn't match the expected instance.
Please ensure that the Firestore types you are using are from the same NPM package.
at Validator.(anonymous function).err [as isQueryValue] (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/firestore/build/src/validate.js:99:27)
at CollectionReference.where (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/firestore/build/src/reference.js:940:25)
package.json
"dependencies": {
....
"#google-cloud/firestore": "^0.16.0",
"firebase-admin": "~6.0.0",
"firebase-functions": "^2.0.5"
}
Now I get it why it throws an error. Because I import Firestore object separately, whereas I should just use Firestore object from Firebase Admin SDK.
What I changed:
remove "#google-cloud/firestore" dependency from package.json
Use admin.firestore.Timestamp object.
index.ts
async someFunction() {
let col = firestore.collection("mycollection");
let now = admin.firestore.Timestamp.now();
let twentyMinsAgo = admin.firestore.Timestamp.fromMillis(now.toMillis() - (1200 * 1000));
col.where('LastEdited', '>=', twentyMinsAgo) //Now ok
.get()
}
when using firebase admin avoid importing and using any of the client side package directly
so instead of
import * as admin from "firebase-admin";
import firebase from "firebase/app";
admin.firestore().collection("name").set({
date: firebase.firestore.Timestamp.now()
})
use this instead
import * as admin from "firebase-admin";
admin.firestore().collection("name").set({
date: admin.firestore.Timestamp.now()
})
2022 EDIT:
For newer version of Firebase ^10.0.2; Timestamp can be imported directly
import * as admin from "firebase-admin";
import { Timestamp } from "firebase-admin/firestore";
admin.firestore().collection("name").set({
date: Timestamp.now(),
})
There is a difference in how the client side and server side packages format Timestamp for some reason.
client
import { Timestamp } from '#angular/fire/firestore';
[
"LastEdited": {
"seconds": 1709272799,
"nanoseconds": 999000000
}
]
server
import { Timestamp } from 'firebase-admin/firestore';
[
"LastEdited": {
"_seconds": 1709272799,
"_nanoseconds": 999000000
}
]
client solution when querying from server
manually create the Timestamp from the return
const timestamp = new Timestamp(data.LastEdited._seconds, data.LastEdited._nanoseconds);

Insert provider for SQLiteObject ionic 3

I'm working on a project on ionic 3 angular 4. I have to connect to a database and do other things...
So I have a page (.ts .html .scss .module.ts), a provider where I use sql. So my problem is this, I have this error :
core.es5.js:1084
ERROR Error: Uncaught (in promise): Error: No provider for SQLiteObject!
Error: No provider for SQLiteObject!
So in module.ts I added in provider flag i put SQLiteObject. But now I get this new error :
compiler.es5.js:1540 Uncaught Error: Can't resolve all parameters for SQLiteObject: (?).
Also if I put SQLite it wants always the SQLiteObject provider.Anyway I never use SQLite just SQLiteObject
import { SQLiteObject } from '#ionic-native/sqlite';
I google and I found that SQLiteObject is not a provider but just an interface.
So? Any idea? I can put code but is long, if you have some idea please comment.
You need to add its class in providers in your app.module.ts file as:
import { SQLiteObject } from '#ionic-native/sqlite';
#NgModule({
declarations: [
MyApp
],
imports: [
//
],
bootstrap: [IonicApp],
entryComponents: [
MyApp
],
providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}, SQLiteObject]
})
export class AppModule {}
You're right SQLiteObject isn't a Provider but you're trying to import it as one. It is a class Object used by the SQLite Provider so you can save the object from your constructor and then use it as this.db from there. FYI: remove the import { SQLiteObject } statement.
private db: SQLiteObject;
constructor(private sqlite: SQLite)
{
this.sqlite.create({
name: 'data.db',
location: 'default'
})
.then((db: SQLiteObject) => {
this.db = db; //set the object to your own var
db.executeSql("CREATE TABLE IF NOT EXISTS ...", {});
});
}

Resources