Angular rxjs fromEvent使用的一个例子
生活随笔
收集整理的這篇文章主要介紹了
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 類似。它需要一個暴露給回調函數當參數的初始值。每次回調函數運行后的返回值會作為下次回調函數運行時的參數。
要獲取更多Jerry的原創文章,請關注公眾號"汪子熙":
總結
以上是生活随笔為你收集整理的Angular rxjs fromEvent使用的一个例子的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 机器学习常用损失函数
- 下一篇: Unity 如何检测鼠标双击事件