将角度异步管道与BehaviourSubject / ReplaySubject和auditTime / debounceTime一起使用

时间:2019-03-08 00:15:45

标签: angular rxjs

我正在尝试使用角度异步管道订阅BehaviourSubject / ReplaySubject。 我也必须使用auditTime或debounceTime运算符来丢弃一些值。

这是一个示例(我使用的是Angular CLI版本7.3.0,仅更改了app.component):

import {Component, OnInit} from '@angular/core';
import {Observable, ReplaySubject, Subject} from 'rxjs';
import {auditTime, tap} from 'rxjs/operators';

@Component({
  selector: 'app-root',
  template: `{{value$ | async}}`,
  styleUrls: ['./app.component.less']
})
export class AppComponent implements OnInit {

  private readonly subjectWithState: Subject<number>;

  constructor() {
    this.subjectWithState = new ReplaySubject(1);
  }

  ngOnInit(): void {
    this.subjectWithState.next(42);
  }

  get value$(): Observable<number> {
    return this.subjectWithState.asObservable()
      .pipe(
        tap(value => console.log(value)),
        auditTime(1000),
      );
  }
}

问题在于主题没有停止发出(单个)值,并且我没有得到任何输出(请参阅控制台日志)。 使用简单的Subject或不使用 auditTime(1000),一切都会按预期进行。

我找不到任何可以解释这种现象的东西。如何在异步管道和BehaviourSubject或ReplaySubject中使用auditTime或debounceTime运算符?

1 个答案:

答案 0 :(得分:0)

每次视图访问value $时,都会创建一个新的可观察对象。不要使用getter属性并创建一个属性,这样就可以访问可观察对象的相同实例。

  value$ = this.subjectWithState.asObservable()
    .pipe(
      tap(value => console.log(value)),
      auditTime(1000),
    );
相关问题