Welcome, guest! Login / Register - Why register?
Psst.. new poll here.
Psst.. new forums here.
Microsoft is blocking us again (TY IP Reputation!) so just use oauth login instead. :)

Paste

Pasted as JavaScript by service ( 7 years ago )
import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument, DocumentReference } from '@angular/fire/firestore';
import { map, take } from 'rxjs/operators';
import { Observable } from 'rxjs';
 
export interface Aluno{
  id?: string,
  nome: string,
  idade: string
}
 
@Injectable({
  providedIn: 'root'
})
export class AlunoService {
  private alunos: Observable<Aluno[]>;
  private alunoCollection: AngularFirestoreCollection<Aluno>;
 
  constructor(private afs: AngularFirestore) {
    this.alunoCollection = this.afs.collection<Aluno>('alunos');
    this.alunos = this.alunoCollection.snapshotChanges().pipe(
      map(actions => {
        return actions.map(a => {
          const data = a.payload.doc.data();
          const id = a.payload.doc.id;
          return { id, ...data };
        });
      })
    );
  }
 
  getAlunos(): Observable<Aluno[]> {
    return this.alunos;
  }
 
  getAluno(id: string): Observable<Aluno> {
    return this.alunoCollection.doc<Aluno>(id).valueChanges().pipe(
      take(1),
      map(aluno => {
        aluno.id = id;
        return aluno
      })
    );
  }
 
  addAluno(aluno: Aluno): Promise<DocumentReference> {
    return this.alunoCollection.add(aluno);
  }
 
  updateAluno(aluno: Aluno): Promise<void> {
    return this.alunoCollection.doc(aluno.id).update({ nome: aluno.nome, idade: aluno.idade });
  }
 
  deleteAluno(id: string): Promise<void> {
    return this.alunoCollection.doc(id).delete();
  }
}

 

Revise this Paste

Your Name: Code Language: