分类

  • 父子组件通信
  • 非父子组件通信

实现

代码如下:

message.service.ts

import { Injectable } from '@angular/core';
import {Subject, Observable} from 'rxjs/'; @Injectable()
export class MessageService { constructor() { }
private subject = new Subject<any>(); sendMessage(something: any) {
this.subject.next(something);
} clearMessage() {
this.subject.next();
} getMessage(): Observable<any> {
return this.subject.asObservable();
}
}

子组件

home.component.ts

import {Component, EventEmitter, OnInit, Output} from '@angular/core';
import {MessageService} from '../message.service'; @Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
message: any; constructor(private messageService: MessageService) {
} ngOnInit() {
} sendMessage(): void { // 发送消息
this.message = 'subject';
this.messageService.sendMessage(this.message);
} clearMessage(): void { // 清除消息
this.messageService.clearMessage();
} }

home.component.html

<input type="button" value="Subject" (click)="sendMessage()">
<input type="button" value="clear" (click)="clearMessage()">

父组件

app.component.ts

import {Component, OnInit} from '@angular/core';
import {MessageService} from './message.service';
import {Subscription} from 'rxjs/Subscription'; @Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
message: any;
subscription: Subscription;
constructor(private messageService: MessageService) {
} ngOnInit(): void {
this.subscription = this.messageService.getMessage()
.subscribe(message => { this.message = message; });
} ngOnDestroy() {
this.subscription.unsubscribe();
}
}

app.component.html

<app-home></app-home>
<div>{{message | json}}</div>
  • 非父子

非父子组件见通信可以通过同一个service来实现。需要注意的是一定要在service中定义一个临时变量来供传递。比如我有两个组件来传递一个Book类型的数据,HomeComponent -> BookComponentBook和service定义如下:

import {EventEmitter, Injectable} from '@angular/core';
import {Subject} from 'rxjs/Subject';
export class Book {
name: string;
price: number;
} @Injectable()
export class BookService {
defaultBook: Book = {name: '《额尔古纳河右岸》', price: 20};
bookEventer: EventEmitter<Book> = new EventEmitter();
}

主页组件HomeComponent,它用来提供数据源,定义如下:

@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
encapsulation: ViewEncapsulation.None
})
export class HomeComponent implements OnInit, OnDestroy {
book: Book; constructor(private bookService: BookService) {
} ngOnInit() {
this.book = {name: '《万历十五年》', price: 10.0};
} ngOnDestroy() {
this.bookService.bookEventer.emit(this.book);
}
}

书籍组件BookComponent,用来接收数据,定义如下:

import {Component, OnInit, ViewEncapsulation} from '@angular/core';
import {Book, BookService} from './book'; @Component({
selector: 'app-book',
templateUrl: './book.component.html',
styleUrls: ['./book.component.css'],
encapsulation: ViewEncapsulation.None
})
export class BookComponent implements OnInit {
protected subscribeBook: Book; constructor(private bookService: BookService) {
bookService.bookEventer.subscribe(book => {
bookService.defaultBook = book;
});
} ngOnInit() {
this.subscribeBook = this.bookService.defaultBook;
}
}

书籍组件模板文件定义如下:

<p>
subscribeBook:{{subscribeBook | json}}
</p>

直接访问书籍模板对应路由的话,显示为:

先访问主页再访问书籍模板对应路由的话,显示为:

参考

RxJS - Subject

Angular 2 组件之间如何通信?

angular2.0+ 模块之间共享service并订阅更新

Angular4学习笔记(十)- 组件间通信的更多相关文章

  1. vue学习笔记(八)组件校验&通信

    前言 在上一章博客的内容中vue学习笔记(七)组件我们初步的认识了组件,并学会了如何定义局部组件和全局组件,上一篇内容仅仅只是对组件一个简单的入门,并没有深入的了解组件当中的其它机制,本篇博客将会带大 ...

  2. RT-Thread学习笔记3-线程间通信 & 定时器

    目录 1. 事件集的使用 1.1 事件集控制块 1.2 事件集操作 2. 邮箱的使用 2.1 邮箱控制块 2.2 邮箱的操作 3. 消息队列 3.1 消息队列控制块 3.2 消息队列的操作 4. 软件 ...

  3. Vue – 基础学习(2):组件间 通信及参数传递

    Vue – 基础学习(2):组件间 通信及参数传递

  4. Blazor入门笔记(6)-组件间通信

    1.环境 VS2019 16.5.1.NET Core SDK 3.1.200Blazor WebAssembly Templates 3.2.0-preview2.20160.5 2.简介 在使用B ...

  5. Angular4学习笔记-目录汇总

    Angular4学习笔记(一)-环境搭建 Angular4学习笔记(二)-在WebStorm中启动项目 Angular4学习笔记(三)- 路由 Angular4学习笔记(四)- 依赖注入 Angula ...

  6. python 全栈开发,Day91(Vue实例的生命周期,组件间通信之中央事件总线bus,Vue Router,vue-cli 工具)

    昨日内容回顾 0. 组件注意事项!!! data属性必须是一个函数! 1. 注册全局组件 Vue.component('组件名',{ template: `` }) var app = new Vue ...

  7. 聊聊Vue.js组件间通信的几种姿势

    写在前面 因为对Vue.js很感兴趣,而且平时工作的技术栈也是Vue.js,这几个月花了些时间研究学习了一下Vue.js源码,并做了总结与输出. 文章的原地址:https://github.com/a ...

  8. python3.4学习笔记(十二) python正则表达式的使用,使用pyspider匹配输出带.html结尾的URL

    python3.4学习笔记(十二) python正则表达式的使用,使用pyspider匹配输出带.html结尾的URL实战例子:使用pyspider匹配输出带.html结尾的URL:@config(a ...

  9. vue组件间通信

    组件间通信(父子,兄弟) 相关链接\组件通信http://www.cnblogs.com/xulei1992/p/6121974.html 学习链接Vue.js--60分钟快速入门http://www ...

随机推荐

  1. 专业方向系列-00-Python与有限元初探

    案例1 给出4个弹簧的劲度系数,离散后,求其总的刚度矩阵. 代码: import numpy as np k1, k2, k3, k4 = 500, 250, 2000, 1000 ki = np.a ...

  2. Python图形编程探索系列-06-按钮批量生产函数

    设计任务 初步设计一个批量生产按钮的函数,根据需要的按钮数量,自动生成多少按钮. 函数设计 import tkinter as tk # 导入tkinter库 root = tk.Tk() # 建立程 ...

  3. mongodb查询后排序

    var user = db.getCollection('user') //user.find({},{_id:0}).pretty().count() user.find({age:{$gte:25 ...

  4. Unity 4.0 中的新动画系统——MecAnim

    分享一个文档资料,关于动画系统的,版本应该很老了,但是有借鉴意义的: Unity 4.0 已于 2012 年 11 月 15 日正式发布,Unity 每一次版本的提升,都给游戏开发者带来惊喜,这一次也 ...

  5. Unity Shader-后处理:Bloom全屏泛光

    一.简介   今天来学习一下全屏Bloom效果,有时候也叫Glow效果,中文一般叫做“全屏泛光”,这是一种可以模拟出HDR的全屏后处理效果,但是实现原理与HDR相差很远,效果比HDR差一些,但是比HD ...

  6. 【T02】理解子网和CIDR的概念

    1.IP地址分为5类,A.B.C.D.E,它们的前缀分别是: A:0 网络个数2^7,主机个数2^24,大概1千6百万 B:10 网络个数2^14,大概1万6千,主机个数2^16,大概6万5千 C:1 ...

  7. 微软BI 之SSRS 系列 - 如何让报表在一页显示,两种常用的技巧

    通常情况下,SSRS 报表在页面内容过多的时候会自动分页.但有的时候当页面内容不是很多,大概最多2页的情况下,或者客户要求所有内容必须在一页显示时,应该如何设置. 实际上,要考虑两种情况:第一种情况是 ...

  8. vim 在行首 行尾添加字符

    在行首添加字符: %s/^/your_word/ 在行尾添加字符 %s/$/your_word/

  9. 内存优化总结:ptmalloc、tcmalloc和jemalloc(转)

    转载于:http://www.cnhalo.net/2016/06/13/memory-optimize/ 概述 需求 系统的物理内存是有限的,而对内存的需求是变化的, 程序的动态性越强,内存管理就越 ...

  10. Oracle 12c: RMAN restore/recover pluggable database

    查看数据库状态 运行在归档模式,可拔插数据库name=pdborcl SQL> archive log list; Database log mode Archive Mode Automati ...