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