Определите класс элемента
item.ts
export class Item {
$key: string;
title: string;
body: string;
timeStamp: number;
active: boolean = true;
}
Создание службы
Объявление переменных и вспомогательных функций
import { Injectable } from '@angular/core';
import { FirebaseListObservable, FirebaseObjectObservable, AngularFireDatabase } from 'angularfire2/database';
import { Item } from './item';
@Injectable()
export class ItemService {
private basePath: string = '/items';
items: FirebaseListObservable<Item[]> = null; // list of objects
item: FirebaseObjectObservable<Item> = null; // single object
constructor(private db: AngularFireDatabase) { }
}
Получение Observables из Firebase
getItemsList(query={}): FirebaseListObservable<Item[]> {
this.items = this.db.list(this.basePath, {
query: query
});
return this.items
}
// Return a single observable item
getItem(key: string): FirebaseObjectObservable<Item> {
const itemPath = `${this.basePath}/${key}`;
this.item = this.db.object(itemPath)
return this.item
}
Создание, обновление и удаление данных
createItem(item: Item): void {
this.items.push(item)
.catch(error => this.handleError(error))
}
// Update an existing item
updateItem(key: string, value: any): void {
this.items.update(key, value)
.catch(error => this.handleError(error))
}
// Deletes a single item
deleteItem(key: string): void {
this.items.remove(key)
.catch(error => this.handleError(error))
}
// Deletes the entire list of items
deleteAll(): void {
this.items.remove()
.catch(error => this.handleError(error))
}
// Default error handling for all actions
private handleError(error) {
console.log(error)
}
Извлечение данных из наблюдаемого
this.item = this.db.object('/item', { preserveSnapshot: true });
this.item.subscribe(snapshot => {
console.log(snapshot.key)
console.log(snapshot.val())
});
Компонент списка элементов — родитель
элементы-list.component.html
<div *ngFor="let item of items | async" > <item-detail [item]='item'></item-detail> </div> <button (click)='deleteItems()'>Delete Entire List</button>
элементы-list.component.ts
export class ItemsListComponent implements OnInit {
public items: FirebaseListObservable<Item[]>;
constructor(private itemSvc: ItemService) { }
ngOnInit() {
this.items = this.itemSvc.getItemsList({limitToLast: 5})
}
deleteItems() {
this.itemSvc.deleteAll()
}
}
Компонент Item Detail — передача данных дочернему компоненту
элементы-detail.component.html
<h5>{{ item.title || 'missing title' }}</h5>
Active: {{ item.active }}
{{ item.timeStamp | date: 'medium' }}
<span (click)='updateTimeStamp()'>Update Timestamp</span>
<span *ngIf='item.active' (click)='updateActive(false)'>Mark Complete</span>
<span *ngIf='!item.active' (click)='updateActive(true)'>Mark Active</span>
<span (click)='deleteItem()'>Delete</span>
элементы-detail.component.
export class ItemDetailComponent {
@Input() item: Item;
constructor(private itemSvc: ItemService) { }
updateTimeStamp() {
let date = new Date().getTime()
this.itemSvc.updateItem(this.item.$key, { timeStamp: date })
}
updateActive(value: boolean) {
this.itemSvc.updateItem(this.item.$key, { active: value })
}
deleteItem() {
this.itemSvc.deleteItem(this.item.$key)
}
}
Проверка формы
<input placeholder="Item Title" class="form-control" [(ngModel)]="item.title" required minlength="2" maxlength="23" #title='ngModel' autofocus> <div *ngIf="title.dirty"> <span *ngIf='title.errors; then errors else valid'>template renders here...</span> </div> <button class="btn btn-primary" (click)='createItem()' [disabled]="!title.valid">Create</button> <ng-template #valid> <p class="text-success">looks good!</p> </ng-template> <ng-template #errors> <p class="text-danger">form contains errors!</p> </ng-template>
Теперь мы можем добавить элемент в базу данных с помощью функции createItem, определенной в сервисе.
export class ItemFormComponent {
item: Item = new Item();
constructor(private itemSvc: ItemService) { }
createItem() {
this.itemSvc.createItem(this.item)
this.item = new Item() // reset item
}
}