zoukankan      html  css  js  c++  java
  • RxJS之Subject主题 ( Angular环境 )

    一 Subject主题

    Subject是Observable的子类。- Subject是多播的,允许将值多播给多个观察者。普通的 Observable 是单播的。

    在 Subject 的内部,subscribe 不会调用发送值的新执行。它只是将给定的观察者注册到观察者列表中,类似于其他库或语言中的 addListener 的工作方式。

    要给 Subject 提供新值,只要调用 next(theValue),它会将值多播给已注册监听该 Subject 的观察者们。

    import { Component, OnInit } from '@angular/core';
    import { Subject } from 'rxjs/Subject';
    import { Subscription } from 'rxjs/Subscription';
    
    @Component({
      selector: 'app-subject',
      templateUrl: './subject.component.html',
      styleUrls: ['./subject.component.css']
    })
    export class SubjectComponent implements OnInit {
    
      constructor() { }
    
      ngOnInit() {
        const subject: Subject<string> = new Subject<string>();
        const subscriptionA: Subscription = subject.subscribe(
          (val: string) => {
            console.log(`observerA: ${val}`);
          }
        );
        const subscriptionB: Subscription = subject.subscribe(
          (val: string) => {
            console.log(`observerB: ${val}`);
          }
        );
        subject.next('Mikey');
        subject.next('Leo');
        subscriptionA.unsubscribe(); // 取消订阅
        subscriptionB.unsubscribe(); // 取消订阅
        subject.next('Raph');
        subject.complete();
      }
    
    }

     每个 Subject 都是观察者。 - Subject 是一个有如下方法的对象: next(v)error(e) 和 complete() ,可以把 Subject 作为参数传给任何 Observable 的 subscribe 方法。

    import { Component, OnInit } from '@angular/core';
    import { Subject } from 'rxjs/Subject';
    import { Subscription } from 'rxjs/Subscription';
    import { from } from 'rxjs/observable/from';
    import { Observable } from 'rxjs/Observable';
    
    @Component({
      selector: 'app-subject',
      templateUrl: './subject.component.html',
      styleUrls: ['./subject.component.css']
    })
    export class SubjectComponent implements OnInit {
    
      constructor() { }
    
      ngOnInit() {
        const subject: Subject<string> = new Subject<string>();
        const subscriptionA: Subscription = subject.subscribe(
          (val: string) => {
            console.log(`observerA: ${val}`);
          }
        );
        const subscriptionB: Subscription = subject.subscribe(
          (val: string) => {
            console.log(`observerB: ${val}`);
          }
        );
    
        const observable: Observable<string> = from(['Raph', 'Don']);
        observable.subscribe(subject);
    
      }
    
    }

     

  • 相关阅读:
    Oracle数据库的经典问题 snapshot too old是什么原因引起的
    在服务器上排除问题的头五分钟
    MySQL的redo log结构和SQL Server的log结构对比
    MySQL优化---DBA对MySQL优化的一些总结
    事务分类
    扩展HT for Web之HTML5表格组件的Renderer和Editor
    iOS平台快速发布HT for Web拓扑图应用
    HT for Web的HTML5树组件延迟加载技术实现
    Zip 压缩、解压技术在 HTML5 浏览器中的应用
    百度地图、ECharts整合HT for Web网络拓扑图应用
  • 原文地址:https://www.cnblogs.com/sea-breeze/p/8992572.html
Copyright © 2011-2022 走看看