1. 程式人生 > >rxjs工具操作符

rxjs工具操作符

一 delay操作符

源Observable延遲指定時間,再開始發射值。

import { Component, OnInit } from '@angular/core';

import { of } from 'rxjs/observable/of';

import { delay } from 'rxjs/operators/delay';

@Component({

  selector: 'app-util',

  templateUrl: './util.component.html',

  styleUrls: ['./util.component.css']

})

export class UtilComponent implements OnInit {

  constructor() { }

   ngOnInit() {

     console.log( new Date() );

    of('Mike', 'Leo').pipe( delay(1000) )

     .subscribe(val => {

        console.log(new Date(), val);

     });

   }

}

二 do/tap操作符

do、tap ( 竊聽 ) 是兩個完全相同的操作符,用於竊聽Observable的生命週期事件,而不會產生打擾。

import { Component, OnInit } from '@angular/core';

import { of } from 'rxjs/observable/of';

import { tap } from 'rxjs/operators/tap';

@Component({

  selector: 'app-util',

  templateUrl: './util.component.html',

  styleUrls: ['./util.component.css']

})

export class UtilComponent implements OnInit {

  constructor() { }

  ngOnInit() {

    // tap在subscribe之前執行

    of('Mikey', 'Leo').pipe(

      tap( val => {

          console.log('tap next', val);

       },

      null,

      () => {

        console.log('tap complete');

      } )

    )

    .subscribe(

        val => {

          console.log('subscribe next', val);

       },

      null,

      () => {

       console.log('subscribe complete');

    } );

    // 沒有訂閱,tap不執行

     of('Raph', 'Don').pipe(

        tap(

            val => {

                console.log('tap next', val);

            },

            null,

            () => {

               console.log('tap complete');

            }

        )

      );

   }

}