Коллекция Firebase не возвращает значение - PullRequest
0 голосов
/ 22 октября 2018

У меня есть Angular @Service и @Component, которые извлекают данные из Firebase Firestore.

Проблема Проблема появляется, когда я пытаюсь вызвать метод getAll ().Возвращает пустой массив.Метод createDocument () работает правильно и создает и экземпляр в Firestore.Метод getDocument (id) возвращает элемент в HTML, но console.log () внутри этого подробного компонента также показывает пустое значение

Bill.ts

export class Bill {
    public timestamp?: Date;
    public amount?: number;
    public products?: Array<ProductOrder> = [];
    public plates?: Array<PlateOrder> = [];
    public id?: string;
}

Сервисный счет.ts

import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from '@angular/fire/firestore';
import { map } from 'rxjs/operators';
import { Bill } from '../../models';

@Injectable({
  providedIn: 'root'
})
export class DaoBillService {

  fsCollectionName = "bills";
  fsCollection: AngularFirestoreCollection<Bill>;
  fsDocument: AngularFirestoreDocument<Bill>;

  constructor(private afs: AngularFirestore) {
    this.fsCollection = this.afs.collection(this.fsCollectionName, ref => ref.orderBy('name', 'asc'))
  }

  createDocument(data) {
    return this.fsCollection.add(data);
  }

  getAll() {
    return this.fsCollection.snapshotChanges().pipe(
      map( res => res.map(a => {
        const data = a.payload.doc.data() as Bill;
        const id = a.payload.doc.id;
        return { id, ...data };
      }))
    )
  }

  getDocument(id) {
    return this.afs.doc(this.fsCollectionName+'/'+id).valueChanges();
  }

}

Служба Employee.ts

import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from '@angular/fire/firestore';
import { map } from 'rxjs/operators';
import { Employee } from '../../models';

@Injectable({
  providedIn: 'root'
})
export class DaoEmployeeService {

  fsCollectionName = "employees";
  fsCollection: AngularFirestoreCollection<Employee>;
  fsDocument: AngularFirestoreDocument<Employee>;

  public employeeOnShift: Employee;

  constructor(private afs: AngularFirestore) {
    this.fsCollection = this.afs.collection(this.fsCollectionName, ref => ref.orderBy('name', 'asc'))
  }

  createDocument(data) {
    return this.fsCollection.add(data);
  }

  getAll() {
    return this.fsCollection.snapshotChanges().pipe(
      map( res => res.map(a => {
        const data = a.payload.doc.data() as Employee;
        const id = a.payload.doc.id;
        return { id, ...data };
      }))
    )
  }

  getDocument(id) {
    return this.afs.doc(this.fsCollectionName+'/'+id).valueChanges();
  }

  openShift(id, data) {
    return this.fsCollection.doc(id).update({ isShift: true, openShiftId: data })
    // this.fsCollection.doc(id).set({name: data.name, price: data.price, amount:data.amount})
  }

  closeShift(id) {
    return this.fsCollection.doc(id).update({ isShift: false, openShiftId: "" })
    // this.fsCollection.doc(id).set({name: data.name, price: data.price, amount:data.amount})
  }

  updateDocument(id, data) {
    this.fsCollection.doc(id).update({ uid: data })
    // this.fsCollection.doc(id).set({name: data.name, price: data.price, amount:data.amount})
  }

}

Component.ts

import { Component, OnInit } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'
import { MatTableDataSource } from '@angular/material';
import { DaoBillService } from '../../../services/dao/dao-bill.service';
import { DaoEmployeeService } from '../../../services/dao/dao-employee.service';

@Component({
  selector: 'app-bill-list',
  templateUrl: './bill-list.component.html',
  styleUrls: ['./bill-list.component.css']
})
export class BillListComponent implements OnInit {

  datasource;
  displayedColumns = ['timestamp', 'amount'];
  items;
  items2;

  constructor(private router: Router, 
              private dao: DaoBillService,
              private daoE: DaoEmployeeService) {
  }

  ngOnInit() {
    this.dao.getAll().subscribe( res => {
      this.items = res
      console.log(res)
      // return nothing
    })
    this.daoE.getAll().subscribe( res => {
      this.items2 = res
      console.log(res)
      // return an array of object
      // services are the same
    })
  }

  applyFilter(filterValue: string) {
    filterValue = filterValue.trim().toLowerCase();
    this.datasource.filter = filterValue;
  }

}

Component.html

    <div class="my-toolbar">
  <button mat-stroked-button color="primary" routerLink="/newbill"><mat-icon>add</mat-icon> nueva factura</button>
</div>


    <mat-card>
        <mat-card-title>
            Lista con facturas
          </mat-card-title>
    <mat-card-content>

      <div class="example-container">
        <div class="example-header">
          <mat-form-field>
            <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Nombre">
          </mat-form-field>
        </div>

        <mat-table #table  [dataSource]="datasource">

          <ng-container matColumnDef="timestamp">
            <mat-header-cell *matHeaderCellDef> Fecha </mat-header-cell>
            <mat-cell *matCellDef="let element">  {{element?.timestamp}}   </mat-cell>
          </ng-container>

          <ng-container matColumnDef="amount">
              <mat-header-cell *matHeaderCellDef> Valor </mat-header-cell>
              <mat-cell *matCellDef="let element"> {{element?.amount}} </mat-cell>
          </ng-container>

          <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
          <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
        </mat-table>
      </div>

    </mat-card-content>
    </mat-card>

    <div class="row">
      <div class="col-md-6 col-xs-12">
          <table class="table">
          <thead>
          <tr>
          <th scope="col">Fecha</th>
          <th scope="col">Valor</th>
          </tr>
          </thead>
          <tbody> 
            <tr *ngFor="let item of items" >
            <td>{{item?.timestamp.toDate() | date: 'MMMM d, h:mm a'}}</td>
            <td>{{item?.amount}}</td>
            </tr>
            </tbody>
          </table>
      </div>
    </div>

<br>
      <div class="row">
        <div class="col-md-6 col-xs-12">
            <table class="table">
            <thead>
            <tr>
            <th scope="col">Name</th>
            <th scope="col">PIN</th>
            </tr>
            </thead>
            <tbody> 
              <tr *ngFor="let item of items2" >
              <td>{{item?.name}}</td>
              <td>{{item?.pin}}</td>
              </tr>
              </tbody>
            </table>
        </div>
      </div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...