如何在Angular 6中使用take(1)?

Der*_*ler 0 rxjs angular rxjs-pipeable-operators rxjs6

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

在下面的代码中,我从Firestore检索文档,然后将其作为可观察的文档使用。

然后,我订阅该可观察的内容,阅读文档的时间戳,并以人类可读的格式设置年龄。效果很好,但是不必每次文档流中都有更改时都执行。它只需要执行一次,因为文档时间戳永远不会改变。

我如何修改此代码以合并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);
      });

    }

  }

}
Run Code Online (Sandbox Code Playgroud)

小智 6

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

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

引入了管道运算符,以更有效的方式利用诸如摇树树之类的功能,允许捆绑优化器仅保留代码中显式引用的管道功能的代码。

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