angular6 Rxjs异步数据流

Observable异步获取数据的基本模型

import { Observable } from 'rxjs';

// Observable异步获取数据
let stream = new Observable((observer) => {
  setTimeout(function () {
    observer.next({
      name: 'huangbiao',
      age: 30
    });
  }, 3000);
});
stream.subscribe(function(data){
  console.dir(data); // 打印的是 {name: 'huangbiao',age: 30}
  debugger
});

取消订阅

import { Observable } from 'rxjs';

// Observable异步获取数据
let stream = new Observable((observer) => {
  setTimeout(function () {
    observer.next({
      name: 'huangbiao',
      age: 30
    });
  }, 3000);
});
let subHandle = stream.subscribe(function(data){
  console.dir(data); // 打印的是 {name: 'huangbiao',age: 30}
  debugger
});
// 取消订阅,就不会执行 订阅内部的方法了
subHandle.unsubscribe();

订阅后多次执行

import { Observable } from 'rxjs';

let stream = new Observable((observer) => {
  let count = 0;
  setInterval(function () {
    count++;
    observer.next('count: ' + count);
  }, 3000);
});

stream.subscribe(function (data) {
  console.log(data);
});

Rxjs 的工具函数

import { Observable } from 'rxjs';
import {map,filter,throttleTime} from 'rxjs/operators';

let stream = new Observable((observer) => {
  let count = 0;
  setInterval(function () {
    count++;
    observer.next(count);
  }, 3000);
});
stream.pipe(map(function (resourceData) {
  return resourceData * resourceData;
})).subscribe(function (data) {
  console.log(data);
});
import {Observable,fromEvent} from 'rxjs';
import {map,filter,throttleTime} from 'rxjs/operators';

var button = document.querySelector('button');
fromEvent(button, 'click').pipe(
  throttleTime(1000)
)
.subscribe(() => console.log(`Clicked`));
  1. map用来处理数据
  2. filter用来过滤数据
  3. throttleTime 用来推迟响应数据

没有更多推荐了,返回首页