Angular中集成了Rxjs库,Rxjs是javascript的一个响应式编程库,它提供了很多api,可以很方便的处理和操作应用中的数据。
我们在自己的angular项目中新建一个组件:
ng generate component rx-button --spec=false
这个组件的代码如下:
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Rx';
@Component({
selector: 'app-rx-button',
templateUrl: './rx-button.component.html',
styleUrls: ['./rx-button.component.css']
})
export class RxButtonComponent implements OnInit {
constructor() { }
ngOnInit() {
const oButton = document.querySelector('button');
const button$ = Observable.fromEvent(oButton, 'click');
button$.throttleTime(1000)
.scan(count => count + 1, 0)
.subscribe(count => console.log(`Clicked ${count} times`));
}
}
这里我们引入了Observable
,引入的时候项目会有一个报错:
我们在项目中安装上rxjs-compat就可以了
npm install rxjs-compat
这段代码要实现的功能是控制一秒钟内最多点击一次。throttleTime(1000)
操作符是在1000毫秒内忽略随后发出的源值,scan
操作符的工作原理与数组的 reduce 类似。它需要一个暴露给回调函数当参数的初始值。每次回调函数运行后的返回值会作为下次回调函数运行时的参数。