【问题标题】:How to use take(1) in Angular 6?如何在 Angular 6 中使用 take(1)?
【发布时间】:2019-01-12 08:21:16
【问题描述】:

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

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

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

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

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);
      });

    }

  }

}

【问题讨论】:

标签: angular rxjs rxjs6 rxjs-pipeable-operators


【解决方案1】:

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

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

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

更多详情请见official docs

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    相关资源
    最近更新 更多