Angular4学习笔记(十)- 组件间通信
分类
- 父子组件通信
- 非父子组件通信
实现
父子
- 父子组件通信一般使用
@Input和@Output即可实现,参考Angular4学习笔记(六)- Input和Output - 通过Subject
- 父子组件通信一般使用
代码如下:
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 -> BookComponent,Book和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学习笔记(十)- 组件间通信的更多相关文章
- vue学习笔记(八)组件校验&通信
前言 在上一章博客的内容中vue学习笔记(七)组件我们初步的认识了组件,并学会了如何定义局部组件和全局组件,上一篇内容仅仅只是对组件一个简单的入门,并没有深入的了解组件当中的其它机制,本篇博客将会带大 ...
- RT-Thread学习笔记3-线程间通信 & 定时器
目录 1. 事件集的使用 1.1 事件集控制块 1.2 事件集操作 2. 邮箱的使用 2.1 邮箱控制块 2.2 邮箱的操作 3. 消息队列 3.1 消息队列控制块 3.2 消息队列的操作 4. 软件 ...
- Vue – 基础学习(2):组件间 通信及参数传递
Vue – 基础学习(2):组件间 通信及参数传递
- Blazor入门笔记(6)-组件间通信
1.环境 VS2019 16.5.1.NET Core SDK 3.1.200Blazor WebAssembly Templates 3.2.0-preview2.20160.5 2.简介 在使用B ...
- Angular4学习笔记-目录汇总
Angular4学习笔记(一)-环境搭建 Angular4学习笔记(二)-在WebStorm中启动项目 Angular4学习笔记(三)- 路由 Angular4学习笔记(四)- 依赖注入 Angula ...
- python 全栈开发,Day91(Vue实例的生命周期,组件间通信之中央事件总线bus,Vue Router,vue-cli 工具)
昨日内容回顾 0. 组件注意事项!!! data属性必须是一个函数! 1. 注册全局组件 Vue.component('组件名',{ template: `` }) var app = new Vue ...
- 聊聊Vue.js组件间通信的几种姿势
写在前面 因为对Vue.js很感兴趣,而且平时工作的技术栈也是Vue.js,这几个月花了些时间研究学习了一下Vue.js源码,并做了总结与输出. 文章的原地址:https://github.com/a ...
- python3.4学习笔记(十二) python正则表达式的使用,使用pyspider匹配输出带.html结尾的URL
python3.4学习笔记(十二) python正则表达式的使用,使用pyspider匹配输出带.html结尾的URL实战例子:使用pyspider匹配输出带.html结尾的URL:@config(a ...
- vue组件间通信
组件间通信(父子,兄弟) 相关链接\组件通信http://www.cnblogs.com/xulei1992/p/6121974.html 学习链接Vue.js--60分钟快速入门http://www ...
随机推荐
- Python3练习题系列(01)
2018-06-13 题目: 根据用户回答做出相应的判断,完成一个“回答-判断”的小游戏 Python3知识点: if, else, elif 实例代码: print("You enter ...
- [模板][P3808]AC自动机(简单版)
Description: 求n个模式串中有几个在文本串中出现 Solution: 模板,详见代码: #include<bits/stdc++.h> using namespace std; ...
- python RandomForest跑feature重要性
其实呢,就是直接调用一个函数的事情... #coding=utf-8 from sklearn.tree import DecisionTreeClassifier from matplotlib.p ...
- 来自极客头条的 35 个 Java 代码性能优化总结
前言 代码优化,一个很重要的课题.可能有些人觉得没用,一些细小的地方有什么好修改的,改与不改对于代码的运行效率有什么影响呢?这个问题我是这么考虑的,就像大海里面的鲸鱼一样,它吃一条小虾米有用吗?没用, ...
- java三大特性--多态(1)
定义 对象具有多种形态 类型 引用的多态: 父类的引用指向自身对象 父类的引用指向子类对象 TrafficTool traffictool=new TrafficTool();//父类的引用指向本身类 ...
- oracle的start with connect by prior如何使用
oracle的start with connect by prior是根据条件递归查询"树",分为四种使用情况: 第一种:start with 子节点ID='...' connec ...
- VS2010链接TFS遇见错误:TF204017,没有访问工作区域,需要一个或者多个必须权限
最近刚刚搭建好服务器,然后准备将VSS源代码迁移到TFS源代码管理服务器上面.在我本机先用的服务器帐号来上传初始化源代码数据库,然后我又用自己的帐号进行迁出代码的时候发生的异常. 造成上述错误,主要是 ...
- IEEE 754二进制浮点数算术标准
可能很多人都遇到过浮点数精度丢失的问题,下面以JavaScript为例. 1 - 0.9 = 0.09999999999999998 纳尼,不应该是0.1么,怎么变成0.099999999999999 ...
- windows域控里,属性和字段映射表
string[] prop = new string[] { "DisplayName", "SamAccountName", "UserPrinci ...
- mac环境下intellij的自定义配置文件位置
~/Library/Preferences/IntelliJIdea2017.2/