首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Angular rxjs fromEvent使用的一个例子

Angular rxjs fromEvent使用的一个例子

作者头像
Jerry Wang
发布2020-09-25 11:11:27
6920
发布2020-09-25 11:11:27
举报

源代码:

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 类似。它需要一个暴露给回调函数当参数的初始值。每次回调函数运行后的返回值会作为下次回调函数运行时的参数。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-09-24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档