(一)Angular5 高级教程--基于 RxJS Subject的组件间通信
2017-11-30 13:46
399 查看
message.service.ts
import { Injectable } from '@angular/core'; import {Observable} from 'rxjs/Observable'; import { Subject } from 'rxjs/Subject'; @Injectable() export class MessageService { private subject = new Subject<any>(); sendMessage(message: string) { this.subject.next({ text: message }); } clearMessage() { this.subject.next(); } getMessage(): Observable<any> { return this.subject.asObservable(); } }
home.component.ts
import { Component } from '@angular/core'; import { MessageService } from './message.service'; @Component({ selector: 'exe-home', template: ` <div> <h1>Home</h1> <button (click)="sendMessage()">Send Message</button> <button (click)="clearMessage()">Clear Message</button> </div>` }) export class HomeComponent { constructor(private messageService: MessageService) {} sendMessage(): void { this.messageService.sendMessage('Message from Home Component to App Component!'); } clearMessage(): void { this.messageService.clearMessage(); } }
app.component.ts
import { Component, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs/Subscription'; import { MessageService } from './message.service'; @Component({ selector: 'my-app', template: ` <div> <div *ngIf="message">{{message.text}}</div> <exe-home></exe-home> </div> ` }) export class AppComponent implements OnDestroy { message: any; subscription: Subscription; constructor(private messageService: MessageService) { this.subscription = this.messageService .getMessage().subscribe( message => { this.message = message; }); } ngOnDestroy() { this.subscription.unsubscribe(); } }
相关文章推荐
- [js高手之路]Vue2.0基于vue-cli+webpack父子组件通信教程
- [js高手之路]Vue2.0基于vue-cli+webpack同级组件之间的通信教程
- [js高手之路]Vue2.0基于vue-cli+webpack父子组件通信教程
- [js高手之路]Vue2.0基于vue-cli+webpack父子组件通信教程
- [js高手之路]Vue2.0基于vue-cli+webpack父子组件通信教程
- Vue2.0基于vue-cli+webpack同级组件之间的通信教程(推荐)
- c#中异步基于消息通信的完成端口的TCP/IP协议的组件实现(源代码) 客户端
- Vue.js学习 Item11 – 组件与组件间的通信
- vue 2 使用Bus.js进行兄弟(非父子)组件通信 简单案例
- JavaScript组件之JQuery(A~Z)教程(基于Asp.net运行环境)[示例代码下载]
- Vue.js--基于$.ajax获取数据并与组件的data绑定
- Mint UI 基于 Vue.js 移动端组件库
- Mint UI -- 基于Vue.js的移动端组件库
- Node.js 基于 ursa 模块的 RSA 加密解密(已与IOS,Android实现加密通信)
- Vue.js组件使用开发实例教程
- Vue.js 系列教程 2:组件,Props,Slots
- (pomelo系列入门教程)深入浅出node.js游戏服务器开发——基于Pomelo的MMO RPG开发
- Vue.js入门学习--父子组件的说明和简单通信(十)
- 效果超赞的基于js的chat组件和图形动画组件
- 初探 amaze-vue( 基于vue.js封装的Amaze UI 组件库)