2

有人可以说明 Angular 6 / rxjs 6 中 take(1) 的语法吗?

在下面的代码中,我从 Firestore 中检索了一个文档,然后将其作为 observable 提供。

然后我订阅那个 observable,读取文档的时间戳,并以人类可读的格式格式化年龄。这很好用,但是它不需要在每次文档流发生更改时都执行。它只需要执行一次,因为文档时间戳永远不会改变。

如何修改此代码以合并take(1),以便仅生成一次年龄字符串并且订阅items不保持打开状态?take(1)我在 Angular / rxjs 版本 6 下找不到任何明确的语法示例。我能找到的所有示例都是针对以前版本的。

import { Component, Input, OnChanges } from '@angular/core';
import { AngularFirestore, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Item } from '../../interfaces/item';

@Component({
  selector: 'app-item',
  templateUrl: './item.component.html',
  styleUrls: ['./item.component.scss']
})
export class ItemComponent implements OnChanges {

  @Input() itemId: string;
  private itemDoc: AngularFirestoreDocument<Item>;
  public item: Observable<Item>;
  public age: string;

  constructor(private afs: AngularFirestore) {}

  ngOnChanges() {

    if ( this.itemId ) {

      this.itemDoc = this.afs.doc<Item>('items/' + this.itemId);
      this.item = this.itemDoc.valueChanges();

      this.item.subscribe(thisitem => {
        this.age = Utils.getFormattedAgeString(thisitem.timestamp);
      });

    }

  }

}
4

1 回答 1

8

您可以使用 Observable 管道函数将管道运算符应用于任何可观察对象,该函数将任意数量的管道运算符作为参数。例如,在您的情况下,您可以在订阅调用之前使用管道,如下所示:

  this.item
    .pipe(
      take(1)
      // and any other pipe operators like map if required
    )
    .subscribe(thisitem => {
      this.age = Utils.getFormattedAgeString(thisitem.timestamp);
    });

引入管道运算符以更有效地利用诸如摇树之类的特性,允许包优化器仅保留代码中明确引用的管道函数的代码。

更多细节可以在官方文档中找到。

于 2018-08-04T21:45:31.783 回答