博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Angular通过订阅观察者对象实现不同组件中数据的实时传递
阅读量:7082 次
发布时间:2019-06-28

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

在angular官方定义中,组件直接的数据交换只要在父子直接传递,但是我们在项目中经常需要在各种层级之间传递数据,下面介绍关于订阅可观察对象实现的数据传递。

首先定义一个服务app.sevice.ts,服务里面new一个SubJect对象:

// app.servie.tsimport { Injectable } from '@angular/core';import { Subject } from 'rxjs/Subject'; @Injectable()export class AppService {   constructor() { }   sub = new Subject
(); }

然后,定义两个组件one-child和two-child在app.compnent显示:

// app.component.ts

其中,one-child里面有一个输入框,绑定keyup方法sendText:

// one-child.component.html

one-child works!

在one-child里面注入app.service,调用sub对象:

import { Component } from '@angular/core';import { AppService } from '../app.service' @Component({  selector: 'one-child',  templateUrl: './one-child.component.html',  styleUrls: ['./one-child.component.scss']})export class OneChildComponent {   constructor(    private appService: AppService  ) { }   sendText(value) {    console.log("one-child: " + value);    this.appService.sub.next(value);  } }

此时,在two-child里面订阅sub对象获取数据:

// two-child.component.tsimport { Component, OnInit } from '@angular/core';import { AppService } from '../app.service'  @Component({  selector: 'two-child',  templateUrl: './two-child.component.html',  styleUrls: ['./two-child.component.scss']})export class TwoChildComponent implements OnInit {    value;  constructor(    private appService: AppService  ) { }    ngOnInit() {    this.appService.sub.subscribe(res => {      this.value = res;      console.log("two-child: " + res);    })  }}

最终我们就可以看到在one-child里面输入的数据在two-child也可以接收到了:

图片描述

最后的话,对于订阅对象,在组件销毁的时候,根据实际情况要取消订阅:

ngOnDestroy() {  this.appService.sub.unsubscribe();}

demo可从下面地址下载体验,下载后运行npm install:

转载地址:http://knvml.baihongyu.com/

你可能感兴趣的文章
(六)注解式控制器详解
查看>>
MahApps.Metro
查看>>
IOS UIWebView的一些用法总结
查看>>
字符串及其他类型数据的比较
查看>>
面向对象二次整理(基础,属性引用,方法引用.绑定方法)
查看>>
Quick-cocos2d-x3.3 Study (十)--------- 添加动画
查看>>
网络学习目录
查看>>
《结对-贪吃蛇游戏-需求分析》
查看>>
入门01
查看>>
Guava包学习--Hash
查看>>
PAT-乙级-01
查看>>
CImage
查看>>
面向对象01
查看>>
[C++参考]私有成员变量的理解
查看>>
五.获得MYSQL数据库自动生成的主键
查看>>
小米4安装apk时出现INSTALL_FAILED_NO_MATCHING_ABIS
查看>>
窗体之间传递值的几种方法
查看>>
springboot开启定时任务 添加定时任务 推送
查看>>
html+css高度100%的时候边框超出,出现滚动条的解决办法,带边框的100%高度
查看>>
最大子段和(洛谷P1115,动态规划递推)
查看>>