{ Adding Firestore }
ng add @angular/fire
{ src/environments/environment.ts }
Update firebaseConfig with credentials that you get when creating Firebase app.
{ Adding Forms }
ng add @angular/forms
{ app.module.ts }
import { FormsModule } from '@angular/forms';
You can always populate more definitions to your interface.
ng g i item
export interface Item {
id?: string;
}
{ Adding service }
ng g s example
{ example.service.ts }
import { Injectable } from '@angular/core';
import {
Firestore,
collection,
doc,
addDoc,
getDoc,
getDocs,
updateDoc,
deleteDoc,
} from '@angular/fire/firestore';
import { Item } from './item';
@Injectable({
providedIn: 'root',
})
export class ExampleService {
constructor(private firestore: Firestore) {}
addItem(item: Item): void {
const ref = collection(this.firestore, 'items');
addDoc(ref, item);
}
async getItem(id: string): Promise<Partial<Item>> {
const docRef = doc(this.firestore, `items/${id}`);
const querySnapshot = await getDoc(docRef);
return { id: querySnapshot.id, ...querySnapshot.data() };
}
async getItems(): Promise<Item[]> {
const colRef = collection(this.firestore, 'items').withConverter(null);
const querySnapshot = await getDocs(colRef);
const items = [];
querySnapshot.forEach((doc) => {
items.push({ id: doc.id, ...doc.data() });
});
return items;
}
async updateItem(id: string, data: any): Promise<void> {
const docRef = doc(this.firestore, `items/${id}`);
return updateDoc(docRef, data);
}
async deleteItem(id: string): Promise<void> {
const docRef = doc(this.firestore, `items/${id}`);
return deleteDoc(docRef);
}
}
ng add @angular/router
Alterations to { app.module.ts }
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: '', component: List },
{ path: 'add', component: AddListComponent },
{ path: 'edit/:id', component: EditListComponent },
];
@NgModule({ imports: [ RouterModule.forRoot(routes) ], exports: [ RouterModule ] })
ng g c list
<table>
<tbody>
<tr *ngFor="let item of items;">
<td>{{ item.id }}</td>
</tr>
</tbody>
</table>
ng g c add-list
ng g c edit-list
Angular Firestore CRUD Guide.
Only logged in members are able to comment on post.