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

x33g5p2x  于2022-03-06 转载在 其他  
字(1.8k)|赞(0)|评价(0)|浏览(583)
  1. import { Component, OnInit } from '@angular/core';
  2. import { CommonService } from '../../services/common.service';
  3. import { Observable } from 'rxjs';
  4. import { map, filter } from 'rxjs/operators';
  5. @Component({
  6. selector: 'app-home',
  7. templateUrl: './home.component.html',
  8. styleUrls: ['./home.component.less']
  9. })
  10. export class HomeComponent implements OnInit {
  11. constructor(public common: CommonService) {
  12. } //注册服务
  13. ngOnInit(): void {
  14. //1. 异步回调
  15. this.common.getDatacb((res) => {
  16. console.log(res)
  17. });
  18. //2. promise获取
  19. this.common.getPromise().then((res) => {
  20. console.log(res);
  21. })
  22. //3. rxjs获取异步数据
  23. var rxData = this.common.geRxjstData();
  24. var p1 = rxData.subscribe(res => {
  25. console.log(res);
  26. })
  27. //4. rxjs获取异步数据执行多次
  28. this.common.getRxIntervalData().subscribe(res => {
  29. console.log(res);
  30. })
  31. // 5. 过一秒以后撤回刚才的动作
  32. setTimeout(() => {
  33. p1.unsubscribe();
  34. }, 1000)
  35. //6. pipe
  36. var stream = this.common.streamFun();
  37. stream.pipe(
  38. filter(val => val % 2 == 0), //过滤
  39. map(value => {
  40. return value * value; // 处理数据
  41. })
  42. )
  43. .subscribe(res => {
  44. console.log(res);
  45. })
  46. }
  47. }
  1. import { Injectable } from '@angular/core';
  2. import { Observable } from "rxjs";//js库
  3. @Injectable({
  4. providedIn: 'root'
  5. })
  6. export class CommonService {
  7. constructor() { }
  8. ///回调函数
  9. getDatacb(cb) {
  10. setTimeout(() => {
  11. cb('getCBdata')
  12. }, 1000)
  13. }
  14. //promise获取
  15. getPromise() {
  16. return new Promise((resolve, reject) => {
  17. setTimeout(() => {
  18. resolve('张三----promise');
  19. // resolve('张三----promise1');
  20. // resolve('张三----promise2');
  21. }, 1000)
  22. })
  23. }
  24. //3. rxjs获取异步数据
  25. geRxjstData() {
  26. return new Observable(observer => {
  27. setTimeout(() => {
  28. var username = '小明 -- rxjs'
  29. observer.next(username);
  30. }, 3000)
  31. })
  32. }
  33. //4. rxjs多次执行
  34. getRxIntervalData() {
  35. return new Observable(observer => {
  36. var count = 0;
  37. setInterval(() => {
  38. count++;
  39. var username = '小明 --rxjs-Interval'
  40. observer.next(username + count);
  41. }, 1000)
  42. })
  43. }
  44. // promise : 不具备撤回 , 以及 多次执行, 但是Rxjs具备
  45. streamFun() {
  46. return new Observable<any>(observer => {
  47. let count = 0;
  48. setInterval(() => {
  49. observer.next(count++);
  50. }, 1000);
  51. });
  52. }
  53. }

相关文章