(精华)2020年8月5日 Angular 异步数据流RxJS的使用

import { Component, OnInit } from '@angular/core';
import { CommonService } from '../../services/common.service';

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

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

  constructor(public common: CommonService) {
  }  //注册服务

  ngOnInit(): void {
    //1. 异步回调
    this.common.getDatacb((res) => {
      console.log(res)
    });

    //2. promise获取
    this.common.getPromise().then((res) => {
      console.log(res);
    })

    //3. rxjs获取异步数据

    var rxData = this.common.geRxjstData();
    var p1 = rxData.subscribe(res => {
      console.log(res);
    })

    //4. rxjs获取异步数据执行多次

    this.common.getRxIntervalData().subscribe(res => {
      console.log(res);
    })


    // 5. 过一秒以后撤回刚才的动作
    setTimeout(() => {
      p1.unsubscribe();
    }, 1000)


    //6. pipe

    var stream = this.common.streamFun();
    stream.pipe(
      filter(val => val % 2 == 0),  //过滤 
      map(value => {
        return value * value;   // 处理数据
      })
    )
      .subscribe(res => {
        console.log(res);
      })

  }

}

import { Injectable } from '@angular/core';
import { Observable } from "rxjs";//js库

@Injectable({
  providedIn: 'root'
})
export class CommonService {

  constructor() { }

  ///回调函数
  getDatacb(cb) {
    setTimeout(() => {
      cb('getCBdata')
    }, 1000)
  }
  //promise获取
  getPromise() {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve('张三----promise');
        // resolve('张三----promise1');
        // resolve('张三----promise2');
      }, 1000)
    })
  }
  //3. rxjs获取异步数据
  geRxjstData() {
    return new Observable(observer => {
      setTimeout(() => {
        var username = '小明 -- rxjs'
        observer.next(username);
      }, 3000)
    })
  }
  //4.  rxjs多次执行
  getRxIntervalData() {
    return new Observable(observer => {
      var count = 0;
      setInterval(() => {
        count++;
        var username = '小明 --rxjs-Interval'
        observer.next(username + count);
      }, 1000)
    })

  }
  // promise : 不具备撤回 , 以及 多次执行, 但是Rxjs具备
  streamFun() {
    return new Observable<any>(observer => {
      let count = 0;
      setInterval(() => {
        observer.next(count++);
      }, 1000);
    });
  }
}

©️2020 CSDN 皮肤主题: 鲸 设计师:meimeiellie 返回首页