Rxjs之建立操做符(Angular環境)

一 of操做符

import { Component, OnInit } from '@angular/core';
import { of } from 'rxjs/observable/of';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'app-create',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css']
})
export class CreateComponent implements OnInit {

  constructor() { }

  ngOnInit() {

    // 從數組建立

    const arr = ['red', 'yellow', 'blue'];
    const colors: Observable<string[]> = of(arr);
    colors.subscribe((colorsArr: string[]) => {
      console.log(colorsArr);
    });

    // 從迭代器對象建立

    const map: Map<string, any> = new Map();
    map.set('fruit', 'orange');
    of(map).subscribe(
      (fruitsMap: Map<string, any>) => {
        console.log(fruitsMap);
      }
    );
  }

}

 

 

二 from操做符

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

@Component({
  selector: 'app-create',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css']
})
export class CreateComponent implements OnInit {

  constructor() { }

  ngOnInit() {

    // 從數組建立

    const arr = ['red', 'yellow', 'blue'];
    const colors: Observable<string> = from(arr);
    colors.subscribe((color: string) => {
      console.log(color);
    });

  }

}

 

 

三 interval操做符

返回從0開始的無限自增整數序列,每一個固定的時間間隔發送。第一次並 沒有立馬去發送, 而是第一個時間段事後才發出。css

import { Component, OnInit } from '@angular/core';
import { interval } from 'rxjs/observable/interval';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'app-create',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css']
})
export class CreateComponent implements OnInit {

  constructor() { }

  ngOnInit() {

    interval(1000).subscribe((val: number) => {
      console.log(val);
    });

  }

}

 

四 range操做符

range 操做符順序發出一個區間範圍內的連續整數, 你能夠決定區間的開始和長度。html

import { Component, OnInit } from '@angular/core';
import { range } from 'rxjs/observable/range';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'app-create',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css']
})
export class CreateComponent implements OnInit {

  constructor() { }

  ngOnInit() {

    range(600, 10).subscribe((val: number) => {
      console.log(val);
    });

  }

}

相關文章
相關標籤/搜索