简体   繁体   English

[Angular]:点击已在模板中使用异步 pipe 的可观察对象

[英][Angular]: Tap on to an observable that has been used in template with async pipe

I have an observable in an angular component that emits a value in 2 seconds interval.我在 angular 组件中有一个 observable,它以 2 秒的间隔发出一个值。 In the template I am printing that observable with async pipe and in the component class, I have piped a tap operator on to that observable to get updates.在模板中,我正在使用async pipe 和组件 class 打印可观察对象,我已将一个点击操作符piped到该可观察对象以获取更新。

Code: app.component.ts代码:app.component.ts

import { Component, OnInit, VERSION } from '@angular/core';
import { Observable, share, shareReplay, tap } from 'rxjs';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  name = 'Angular ' + VERSION.major;

  obs = new Observable((observer) => {
    let i = 0;
    setInterval(() => {
      observer.next(i++);
    }, 2000);
  })

  ngOnInit() {
    this.obs.pipe(share(),tap((data) => {
      console.log(data); //should print 1,2,3
    }));
  }

}

app.component.html app.component.html

<hello name="{{ name }}"></hello>
<p>{{ obs | async }}</p>

But the tap operator is not executing here.但是点击操作符并没有在这里执行。 As the async operator already subscribes to the observable, what is the way that I can tap on that observable and get updates?由于异步操作员已经订阅了 observable,我可以通过什么方式点击该 observable 并获取更新?

stackblitz code example stackblitz 代码示例

Use a pipe when creating the observable, and instead of setInterval there is an interval :在创建 observable 时使用pipe ,而不是setInterval有一个interval

obs = interval(2000)
  .pipe(
    // map()
    share(),
    tap((data) => {
      console.log(data);
    }),
  );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM