Skip to content

Instantly share code, notes, and snippets.

@nntndfrk
Created April 27, 2019 12:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nntndfrk/cd6ffbfaad81ae4221062f37f4f0d659 to your computer and use it in GitHub Desktop.
Save nntndfrk/cd6ffbfaad81ae4221062f37f4f0d659 to your computer and use it in GitHub Desktop.
import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from '@angular/fire/firestore';
import { Source } from '../../shared/models/source';
import { Observable } from 'rxjs/internal/Observable';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class SourceService {
private sourcesCollection: AngularFirestoreCollection<Source>;
private sourceDoc: AngularFirestoreDocument<Source>;
source: Observable<Source>;
constructor(private angularFirestore: AngularFirestore) {
this.sourcesCollection = this.angularFirestore.collection('sources');
}
/*
* Gets source from database
* @param {string} id - source id
* @returns {Observable} of source data without id
*/
getSourceById(id): Observable<Source> {
return this.angularFirestore.doc<any>(`sources/${id}`).valueChanges();
}
/*
* Gets all sources from database
*/
getSources() {
return this.sourcesCollection.snapshotChanges().pipe(map(changes => {
return changes.map(value => {
const data = value.payload.doc.data() as Source;
const id = value.payload.doc.id;
return {id, ...data};
});
}));
}
/*
* Adds source into database
* @param {Object} source - the source
* which it has to add
*/
addSource(source: Source) {
return this.sourcesCollection.add(source);
}
/*
* Deletes source from database
* @param {string} id - the source id
* which it has to delete
*/
deleteSource(id: string) {
this.sourceDoc = this.angularFirestore.doc(`sources/${id}`);
return this.sourceDoc.delete();
}
/*
* Updates source data in database
* @param {Object} source - the source
* which we have to edit.
* @param id {string} id - we have to
* get from route parameters
*/
updateSource(id: string, source: Source) {
this.sourceDoc = this.angularFirestore.doc(`sources/${id}`);
return this.sourceDoc.update(source);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment