博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
angular service 进行组件通信
阅读量:4355 次
发布时间:2019-06-07

本文共 1343 字,大约阅读时间需要 4 分钟。

MessageService 代码如下

import { Injectable } from '@angular/core';import { Subject } from 'rxjs';@Injectable({  providedIn: 'root'})export class MessageService {  private messageSource = new Subject
(); message$ = this.messageSource.asObservable(); messageAction(name: string) { this.messageSource.next(name); }}

发送消息的组件 代码如下

ts

import { Component} from '@angular/core';import { MessageService } from '../service/message.service';@Component({  selector: 'app-send',  templateUrl: './send.component.html',  styleUrls: ['./send.component.css']})export class SendComponent {  constructor(private messageService: MessageService) { }  sendMessage(action: string) {    this.messageService.messageAction(action);  }

html

接收消息的组件

ts

import { Component, OnInit, OnDestroy } from '@angular/core';import { MessageService } from './service/message.service';@Component({  selector: 'app-root',  templateUrl: './app.component.html',  styleUrls: ['./app.component.css']})export class AppComponent implements OnInit, OnDestroy {  action: string;  sub: Subscription;  ngOnInit(): void {    this.messageService.message$.subscribe(action => this.action = action);  }  ngOnDestroy(): void {    this.sub.unsubscribe(); //不要忘记取消订阅  }  constructor(private messageService: MessageService) {  }

转载于:https://www.cnblogs.com/Godfunc/p/9848713.html

你可能感兴趣的文章
【转】C#中如何实现左截取和右截取字符串
查看>>
代码整洁之道
查看>>
HDU3657 Game(最小割)
查看>>
LinkedList源码解析
查看>>
为什么领域模型对于架构师如此重要? https://blog.csdn.net/qq_40741855/article/details/84835212...
查看>>
序言 - PHP零基础快速入门
查看>>
Zabbix_agnet部署
查看>>
shell --for双括号循环
查看>>
NIO
查看>>
UNICODE与ANSI的区别
查看>>
python学习第八讲,python中的数据类型,列表,元祖,字典,之字典使用与介绍
查看>>
ClickOnce部署(3):使用证书
查看>>
写程序需要注意的几点
查看>>
Android网络笔记
查看>>
c++面向对象程序设计 谭浩强 第三章答案
查看>>
hadoop配置项笔记 - streaming
查看>>
函数与模块
查看>>
Swift的期待
查看>>
SQLite中的表达式
查看>>
Android系统容量检测 —— Environment 和StatFs
查看>>