【问题标题】:Use angular async pipe with BehaviourSubject/ReplaySubject and auditTime/debounceTime将角度异步管道与 BehaviourSubject/ReplaySubject 和 auditTime/debounceTime 一起使用
【发布时间】:2019-03-08 00:15:45
【问题描述】:

我正在尝试使用角度异步管道订阅 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),一切都按预期工作。

我找不到任何可以解释这种行为的东西。如何将 auditTime 或 debounceTime 运算符与异步管道和 BehaviourSubject 或 ReplaySubject 一起使用?

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

    每次视图访问 value$ 时都会创建一个新的 observable。不要使用 getter 属性并创建属性以便访问 observable 的同一实例。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-05
      • 1970-01-01
      • 2019-07-15
      • 2020-11-27
      • 1970-01-01
      • 2021-10-19
      • 2019-04-10
      • 2021-02-02
      相关资源
      最近更新 更多