首页 >> 大全

Angular通过订阅观察者对象实现不同组件中数据的实时传递

2023-09-08 大全 35 作者:考证青年

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

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

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

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

// app.component.ts

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

// one-child.component.html

one-child works!

在one-child里面注入app.,调用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.ts
import { 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 :

关于我们

最火推荐

小编推荐

联系我们


版权声明:本站内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 88@qq.com 举报,一经查实,本站将立刻删除。备案号:桂ICP备2021009421号
Powered By Z-BlogPHP.
复制成功
微信号:
我知道了