如何从Firebase数据库加入集合并在Angular 4中打印数据

时间:2017-12-06 11:47:48

标签: angular firebase firebase-realtime-database google-cloud-firestore

我正在尝试合并/加入Firestore中两个单独集合的数据。我看到的数据模型如下:

customers--+
           |
           +--<generatedId>+
           |               +-- fullName
           |               +-- phone
           |
           +--<generatedId>+
                           +-- fullName
                           +-- phone

tasks------+
           |
           +--<generatedId>+
           |               +-- dateCreated
           |               +-- customerId 
           |
           +--<generatedId>+
                           +-- dateCreated
                           +-- customerId

注意:customerId是customers集合

中的文档ID

tasks.component.ts:

import { Component, OnInit } from '@angular/core';
import { TasksService } from '../tasks.service';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'app-tasks',
  templateUrl: './tasks.component.html',
  styleUrls: ['./tasks.component.css']
})

export class TasksComponent implements OnInit {

  tasks: any[];

  constructor(private _tasksService: TasksService) { }

  ngOnInit() {
    this._tasksService.getTasks().subscribe(tasks => {
      const taskArr = [];
      tasks.forEach(element => {
        const customer = this._tasksService.getCustomer(element.data.customerId);
        taskArr.push({
          id: element.id,
          data: element.data,
          cus: customer
        });
      });
      this.tasks = taskArr;
    });

}

task.service.ts:

import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';

@Injectable()
export class TasksService {

  tasksCollection: AngularFirestoreCollection<any>;
  customerDocument: AngularFirestoreDocument<any>;

  constructor(public afs: AngularFirestore) {
  }

  getTasks() {

    /* Returns list of the tasks */

    this.tasksCollection = this.afs.collection<any>('tasks');
    return this.tasksCollection.snapshotChanges().map(actions => {
      return actions.map(a => {
        const data = a.payload.doc.data();
        const id = a.payload.doc.id;
        return { id, data };
      });
    });
  }

  getCustomer(id: string) {

    / * Returns customer information details */

    this.customerDocument = this.afs.doc<any>('customers/' + id);
    return this.customerDocument.valueChanges();
  }
}

app.component.html:

  <ul *ngFor="let task of tasks">
    <li>
      {{task.id}} 
      {{task.data.dateCreated | date:'M/dd/yyyy, HH:mm a'}}
      {{(task.cus | async)?.fullName}}
      {{(task.cus | async)?.phone}}) 
    </li>
  </ul>

我觉得这个代码虽然有效但并不是最佳和正确的。请问你能分享一下如何做得更好吗?

0 个答案:

没有答案