Retrive firestore documentId并添加到html

时间:2017-12-02 03:13:53

标签: javascript angular angularfire2 google-cloud-firestore

我正在构建我的第一个Angular应用程序,而我正在尝试集成firestore。 到目前为止,我能够从firestore检索数据,并使用快照记录id,但我无法将它们全部整合在一起。

有没有办法将id添加到客户端模型?

我正在阅读angularfire2文档,其中说我们不能使用$ key属性,现在我们应该使用快照,但我无法弄明白。

谢谢

这是我的服务

@Injectable()
export class ClientService {
  clientsCollection: AngularFirestoreCollection<Client>;
  clients: Observable<Client[]>;
  snapshot: any;
  constructor(private afs: AngularFirestore) {
    this.clientsCollection = this.afs.collection('clients');
    this.clients = this.clientsCollection.valueChanges();
    // snapshot for id/metadata
    this.snapshot = this.clientsCollection.snapshotChanges()
      .map(arr => {
        console.log(arr);
      });
  }
}

我的client.component.ts

@Component({
  selector: 'app-clients',
  templateUrl: './clients.component.html',
  styleUrls: ['./clients.component.css']
})
export class ClientsComponent implements OnInit {
  clients: Client[];
  snapshots: any[];
  constructor(
  public clientService: ClientService
  ){}

ngOnInit(){
  this.clientService.clients.subscribe(clients => {
    this.clients = clients;
  });
}
}

我的client.component.html

<table *ngIf="clients?.length > 0; else noClients" class="table table-striped">
  <thead class="thead-inverse">
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Email</th>
      <th>Balance</th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let client of clients">
      <td></td>
      <td>{{ client.firstName }} {{ client.lastName }}</td>
      <td>{{ client.email }}</td>
      <td>{{ client.balance }}</td>
      <td><a href="" class="btn btn-secondary btn-sm">Details</a></td>
    </tr>
  </tbody>

</table>

<ng-template #noClients>
  <hr>
  <h5>There are no clients in the system</h5>
</ng-template>

this is what I have so far

1 个答案:

答案 0 :(得分:1)

您可以在angularfire2 documents

中找到答案
    export class AppComponent {
  private shirtCollection: AngularFirestoreCollection<Shirt>;
  shirts: Observable<ShirtId[]>;
  constructor(private readonly afs: AngularFirestore) {
    this.shirtCollection = afs.collection<Shirt>('shirts');
    // .snapshotChanges() returns a DocumentChangeAction[], which contains
    // a lot of information about "what happened" with each change. If you want to
    // get the data and the id use the map operator.
    this.shirts = this.shirtCollection.snapshotChanges().map(actions => {
      return actions.map(a => {
        const data = a.payload.doc.data() as Shirt;
        const id = a.payload.doc.id;
        return { id, ...data };
      });
    });
  }
}

和这个模板

 <ul>
  <li *ngFor="let shirt of shirts | async">
    {{ shirt.id }} is {{ shirt.price }}
  </li>
</ul>