💡 Nodes → different structures
Firebase in Angular Applications | Mosh - YouTube
https://github.com/angular/angularfire ← notice on the version of angular and firebase!!
environment.ts
to store api, keys
export class ... {
constructor(db: AngularFireDatabase) {
db
.list() // reading list of objects
// .object() // reading 1 object
}
}
Type: DocumentChangeAction
-> ref which gives .type
and .payload
interface DocumentChangeAction {
//'added' | 'modified' | 'removed';
type: DocumentChangeType;
payload: DocumentChange;
}
interface DocumentChange {
type: DocumentChangeType;
doc: DocumentSnapshot;
oldIndex: number;
newIndex: number;
}
interface DocumentSnapshot {
exists: boolean;
ref: DocumentReference;
id: string;
metadata: SnapshotMetadata;
data(): DocumentData;
get(fieldPath: string): any;
}
Examples
@Component({
selector: 'app-root',
template: `
<ul>
<li *ngFor="let item of items | async">
<input type="text" #updatetext [value]="item.text" />
<button (click)="updateItem(item.key, updatetext.value)">Update</button>
<button (click)="deleteItem(item.key)">Delete</button>
</li>
</ul>
<input type="text" #newitem />
<button (click)="addItem(newitem.value)">Add</button>
<button (click)="deleteEverything()">Delete All</button>
`,
})
export class AppComponent {
itemsRef: AngularFireList<any>;
items: Observable<any[]>;
constructor(db: AngularFireDatabase) {
this.itemsRef = db.list('messages');
// Use snapshotChanges().map() to store the key
this.items = this.itemsRef.snapshotChanges().pipe(
map(changes =>
changes.map(c => ({ key: c.payload.key, ...c.payload.val() }))
)
);
}
addItem(newName: string) {
this.itemsRef.push({ text: newName });
}
updateItem(key: string, newText: string) {
this.itemsRef.update(key, { text: newText });
}
deleteItem(key: string) {
this.itemsRef.remove(key);
}
deleteEverything() {
this.itemsRef.remove();
}
}
@angular/fire
provides AngularFireDatabase
service that allows us to work with the Realtime Database.
import { AngularFireDatabase} from '@angular/fire/database';
export class TutorialService {
constructor(private db: AngularFireDatabase) { }
}
snapshotChanges()
https://github.com/angular/angularfire/blob/master/docs/rtdb/lists.md#snapshotchanges
.list('conversations/-MSYAXjrlcXdzZAIRp_U')
.snapshotChanges()
.pipe(
map((data: AngularFireAction<DatabaseSnapshot<any>>[]) =>{
/*###Thi*/ console.log('data: ', data);
return ...
}
)
);
// output
0: {payload: DataSnapshot, type: "value", prevKey: null, key: "facebook"}
1: {payload: DataSnapshot, type: "value", prevKey: "facebook", key: "google"}
2: {payload: DataSnapshot, type: "value", prevKey: "google", key: "sandbox"}
3: {payload: DataSnapshot, type: "value", prevKey: "sandbox", key: "web"}
length: 4
ref
References (orderByChild
, limitToLast
, ...) → official doc. but Angular uses this