首页 > 其他 > 详细

Angular 发布订阅模式实现不同组件之间通讯

时间:2019-12-10 17:36:19      阅读:170      评论:0      收藏:0      [点我收藏+]

在我们项目中要实现不同组件之间通讯,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);
    });
  }

}

 

Angular 发布订阅模式实现不同组件之间通讯

原文:https://www.cnblogs.com/hlkawa/p/12017926.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!