天天看點

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:

Angular rxjs fromEvent使用的一個例子

scan 操作符的工作原理與數組的 reduce 類似。它需要一個暴露給回調函數當參數的初始值。每次回調函數運作後的傳回值會作為下次回調函數運作時的參數。

繼續閱讀