npm install firebase @angular/fire --save
...
import { AngularFireModule } from '@angular/fire';
import { AngularFirestoreModule } from '@angular/fire/firestore';
const config = {
apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxxxxxxxxxxxxxx",
databaseURL: "xxxxxxxxxxxxxxxxxxxxxxxxxx",
storageBucket: "xxxxxxxxxxxxxxxxxxxxx",
messagingSenderId: "xxxxxxxxxxxxxxxxxxxxxxxxxx"
};
@NgModule({
imports: [
...
AngularFireModule.initializeApp(config),
AngularFirestoreModule
],
declarations: [ ... ],
bootstrap: [ ... ]
})
export class AppModule { }
...
import { AngularFirestore } from '@angular/fire/firestore';
...
export class AppComponent {
constructor(public db: AngularFirestore) {
}
}
- Add a new doc (auto generated id)
this.db.collection("cities").add({
name: "Tokyo",
country: "Japan"
})
.then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
- Add a new doc (with custom id)
var docData = {
stringExample: "Hello world!",
booleanExample: true,
numberExample: 3.14159265
};
this.db.collection("data").doc("one").set(docData).then(function() { // <<<< "one" is the custom id
console.log("Document successfully written!");
});
If a doc already exists with same id, it will overwrite the contents While adding new doc if the collection doesn't exist, it will create the collection also So to create a collection, atleast one doc is required
There are basically two ways to read data
- Call a method to get the data
- Set a listener to receive data-change events
1.1 Call a method to get a specific doc data
let docRef = this.db.collection("cities").doc("SF");
docRef.get().then(function(doc) {
if (doc.exists) {
console.log("Document data:", doc.data());
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});
1.2 To get all doc from a specific collection
this.db.collection("cities").get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
});
1.3 Get multiple documents from a collection based on some filter
this.db.collection("cities").where("capital", "==", true)
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});
2.1 Get the value instantly and also listen for updates
this.db.collection("cities").where("capital", "==", true)
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});