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();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM