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 類似。它需要一個暴露給回調函數當參數的初始值。每次回調函數運行後的返回值會作爲下次回調函數運行時的參數。