zoukankan      html  css  js  c++  java
  • Angular 发布订阅模式实现不同组件之间通讯

    在我们项目中要实现不同组件之间通讯,Angular的@Input和@Output只能实现有父子组件的限制,如果是复杂跨组件实现不同组件可以通过共享变量的方式实现,比如这个博客的思路:https://www.cnblogs.com/hlkawa/p/6815023.html,或者是基于h5的 localStorage + 轮询机制实现,不过现在以发布订阅的模式来实现不同组件之间的通讯会更加简洁,直接贴代码:

    Service服务创建主题

    #注意angular5和angular6以上的版本可能Subject和Observable引入的路径有所不同 
    import { Subject } from 'rxjs/Subject';
    import { Observable } from 'rxjs/observable';
    
    export class MessageService {
        private subject = new Subject<any>();
    
        send(message: any) {
            this.subject.next(message);
        }
    
        get(): Observable<any> {
            return this.subject.asObservable();
        }
    }

    发布者 组件

    import { Component, OnInit } from '@angular/core';
    import { Subject } from 'rxjs/Subject';
    import { MessageService } from '../../service/message.service';
    
    @Component({
      selector: 'app-send-demo',
      templateUrl: './send-demo.component.html',
      styleUrls: ['./send-demo.component.sass']
    })
    export class SendDemoComponent implements OnInit {public name = 'ok';
      constructor(public srv: MessageService) { }
      ngOnInit() {
      }
    
      clickBtn() {
        this.srv.send(this.name);
      }
    
    }

    消费者组件

    import { Component, OnInit } from '@angular/core';
    import { MessageService } from '../../service/message.service';
    
    @Component({
      selector: 'app-subscribe-home',
      templateUrl: './subscribe-home.component.html',
      styleUrls: ['./subscribe-home.component.sass']
    })
    export class SubscribeHomeComponent implements OnInit {
    
      constructor(public srv: MessageService) { }
      public message = '';
      ngOnInit() {
        this.srv.get().subscribe((result) => {this.message = result;
          console.log(this.message);
        });
      }
    
    }

    但是上面基于Subject的方式,有一个问题,就是在消息发布者发送多次消息,消息消费者累计式的接受消息,出现资源的浪费。如果我们消费每次消费只想消费最新一条消息可以使用Subject的变体之一是BehaviorSubject,具有“当前值”的概念。它存储发布给消费者的最新值,每当新的Observer订阅时,它将立即从BehaviorSubject中获得“当前值” 。

    相关的伪代码如下:

     // 定义 BehaviorSubject
     public bolg: Blog;
      private blogSubject = new BehaviorSubject<Blog>(this.bolg);
    
      sendBlog(blog:Blog) {
        this.blogSubject.next(blog);
      }
    
      getBlog(): Blog {
          return this.blogSubject.getValue()
      }
    --------------------------------------------------------- // 提供者 this.blogService.sendBlog(blog);
    ---------------------------------------------------------- // 消费者 this.blog = this.blogService.getBlog();
  • 相关阅读:
    美团霸面---我想说说心里话。
    docker在ubuntu14.04下的安装笔记
    ubuntu14.04 upgrade出现【Ubuntu is running in low-graphics mode】问题的一个解决办法
    Python2和Python3在windows下共存
    Python发送邮件
    Python在安装第三方模块遇到的问题及解决办法
    127.0.0.1和localhost完全相等吗?
    vim总结
    linux shell学习笔记
    Jenkins +JUnit
  • 原文地址:https://www.cnblogs.com/hlkawa/p/12017926.html
Copyright © 2011-2022 走看看