如何在Angular 5中访问Observable <array [] =“”>的最后一个元素

时间:2018-02-09 20:47:27

标签: angular typescript observable angularfire2

我正在使用angularfire2和Angular 5来创建我的项目。 以下是代码。

import { Component, OnInit } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument  } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';

export interface Details {
  name: string;
  phone: number;
  pphone: number;
  id: number;
}

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

  private studentCollection: AngularFirestoreCollection<Details>;
  students: Observable<Details[]>;

  constructor(db: AngularFirestore) {
    this.studentCollection = db.collection<Details>('collectionName');
    this.students = this.studentCollection.valueChanges();
  }

  ngOnInit() {
  }

我想要的是访问存储在students:Observable<Details[]>中的最后一个json对象 有没有这样做?
对于任何发布错误,我们深表歉意。

1 个答案:

答案 0 :(得分:1)

如果只需要值

this.studentCollection.valueChanges().subscribe(details
                                  => console.log(details[details.length-1]))

如果您需要它作为可观察的

修改:在Aluan Haddad的评论之后添加了mergeAll()

lastStudent$ = this.studentCollection.valueChanges().mergeAll().takeLast(1);