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

}
12-27 10:30