Angular rxjs fromEvent使用的一个例子

时间:2022-07-25
本文章向大家介绍Angular rxjs fromEvent使用的一个例子,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

源代码:

import { Component, OnInit } from '@angular/core';
import { JerrySandBoxService } from './jerrySandBoxService';
import { GreetingService } from './greeting.service';
import { fromEvent } from 'rxjs';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  title = 'sandbox';
    constructor(private jerryService: JerrySandBoxService,
                private englishGreet: GreetingService){
      // this.jerryService.print();
      this.jerryService.print2();
      console.log(this.englishGreet.greet('Jerry'));
  }
  ngOnInit(): void {
    const button = document.querySelector('button');
    fromEvent(button, 'click').subscribe(() => {
      console.log('I am Clicked!');
    });
  }

  jerryTest(){
    console.log('Hello');
  }


}

在html里定义一个button:

点击之后,看到输出:

可以改得更高级一些:

  ngOnInit(): void {
    const button = document.querySelector('button');
    fromEvent(button, 'click').pipe(scan(count => count + 1, 0))
    .subscribe(count => console.log(`Clicked ${count} times`));
  }

测试输出:

scan 操作符的工作原理与数组的 reduce 类似。它需要一个暴露给回调函数当参数的初始值。每次回调函数运行后的返回值会作为下次回调函数运行时的参数。