RxJS conversion operator (Angular environment)

a map operator

Similar to the well-known  Array.prototype.map method, this operator applies a projection function to each value and emits the projected result in the output 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() { }

  by OnInit () {
    of(1, 2).pipe(map(val => val * 10))
      .subscribe(val => {
        console.log(val);
      });
  }

}

 

Two switchMap operators

Map each source value into an Observable, and output this newly generated inner Observable.

When the source value changes, stop the old Observable and its subscriptions, and output the new 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() { }

  by OnInit () {
    interval(5000)
      .pipe(
        switchMap(
          val => interval(1000)
            .pipe(map(val2 => val * 100 + val2))
        )
      )
      .subscribe(val => {
        console.log(val);
      });
  }

}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325158058&siteId=291194637