RxJS之轉化操作符 ( Angular環境 )
阿新 • • 發佈:2018-04-30
implement proto img array nts size 內部 .com 方法 二 switchMap操作符
一 map操作符
類似於大家所熟知的 Array.prototype.map
方法,此操作符將投射函數應用於每個值 並且在輸出 Observable 中發出投射後的結果。
import { Component, OnInit } from ‘@angular/core‘; import { Observable } from ‘rxjs/Observable‘; import { of } from ‘rxjs/observable/of‘; import { map } from ‘rxjs/operators/map‘; @Component({ selector: ‘app-convert‘, templateUrl: ‘./convert.component.html‘, styleUrls: [‘./convert.component.css‘] }) export class ConvertComponent implements OnInit { constructor() { } ngOnInit() { of(1, 2).pipe(map(val => val * 10)) .subscribe(val => { console.log(val); }); } }
二 switchMap操作符
將每個源值映射成 Observable,並輸出這個新生成的內部Observable。
源值發生變化時,停止舊的Observable及其訂閱,輸出新的Observable。
import { Component, OnInit } from ‘@angular/core‘; import { Observable } from ‘rxjs/Observable‘; import { interval } from ‘rxjs/observable/interval‘; import {map} from ‘rxjs/operators/map‘; import { switchMap } from ‘rxjs/operators/switchMap‘; @Component({ selector: ‘app-convert‘, templateUrl: ‘./convert.component.html‘, styleUrls: [‘./convert.component.css‘] }) export class ConvertComponent implements OnInit { constructor() { } ngOnInit() { interval(5000) .pipe( switchMap( val => interval(1000) .pipe(map(val2 => val * 100 + val2)) ) ) .subscribe(val => { console.log(val); }); } }
RxJS之轉化操作符 ( Angular環境 )