聊聊Angular中组件之间怎么通信
时间:2022-04-24 [网络编程]作者:fabuyuan 浏览:7 次
上一篇,我们讲了 Angular 结合 NG-ZORRO 快速开发。前端开发,很大程度上是组件化开发,永远离不开组件之间的通信。那么,在 Angular
开发中,其组件之间的通信是怎么样的呢?【相关教程推荐:《angular教程》】
本文纯文字,比较枯燥。因为控制台打印的东西比较鸡肋,所以就不配图了,嗯~希望读者跟着说明代码走一遍更容易吸收~
1. 父组件通过属性传递值给子组件
相当于你自定义了一个属性,通过组件的引入,将值传递给子组件。Show you the CODE
。
<!-- parent.component.html --> <app-child [parentProp]="'My kid.'"></app-child>
在父组件中调用子组件,这里命名一个 parentProp
的属性。
// child.component.ts import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.scss'] }) export class ChildComponent implements OnInit { // 输入装饰器 @Input() parentProp!: string; constructor() { } ngOnInit(): void { } }
子组件接受父组件传入的变量 parentProp
,回填到页面。
<!-- child.component.html --> <h1>Hello! {{ parentProp }}</h1>
2. 子组件通过 Emitter 事件传递信息给父组件
通过 new EventEmitter()
将子组件的数据传递给父组件。
// child.component.ts import { Component, OnInit, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.scss'] }) export class ChildComponent implements OnInit { // 输出装饰器 @Output() private childSayHi = new EventEmitter() constructor() { } ngOnInit(): void { this.childSayHi.emit('My parents'); } }
通过 emit
通知父组件,父组件对事件进行监听。
// parent.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-communicate', templateUrl: './communicate.component.html', styleUrls: ['./communicate.component.scss'] }) export class CommunicateComponent implements OnInit { public msg:string = '' constructor() { } ngOnInit(): void { } fromChild(data: string) { // 这里使用异步 setTimeout(() => { this.msg = data }, 50) } }
在父组件中,我们对 child
组件来的数据进行监听后,这里采用了 setTimeout
的异步操作。是因为我们在子组件中初始化后就进行了 emit
,这里的异步操作是防止 Race Condition
竞争出错。
我们还得在组件中添加 fromChild
这个方法,如下:
<!-- parent.component.html --> <h1>Hello! {{ msg }}</h1> <app-child (childSayHi)="fromChild($event)"></app-child>
3. 通过引用,父组件获取子组件的属性和方法
我们通过操纵引用的方式,获取子组件对象,然后对其属性和方法进行访问。
我们先设置子组件的演示内容:
// child.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.scss'] }) export class ChildComponent implements OnInit { // 子组件的属性 public childMsg:string = 'Prop: message from child' constructor() { } ngOnInit(): void { } // 子组件方法 public childSayHi(): void { console.log('Method: I am your child.') } }
我们在父组件上设置子组件的引用标识 #childComponent
:
<!-- parent.component.html --> <app-child #childComponent></app-child>
之后在 javascript
文件上调用:
import { Component, OnInit, ViewChild } from '@angular/core'; import { ChildComponent } from './components/child/child.component'; @Component({ selector: 'app-communicate', templateUrl: './communicate.component.html', styleUrls: ['./communicate.component.scss'] }) export class CommunicateComponent implements OnInit { @ViewChild('childComponent') childComponent!: ChildComponent; constructor() { } ngOnInit(): void { this.getChildPropAndMethod() } getChildPropAndMethod(): void { setTimeout(() => { console.log(this.childComponent.childMsg); // Prop: message from child this.childComponent.childSayHi(); // Method: I am your child. }, 50) } }
这种方法有个限制?,就是子属性的修饰符需要是 public
,当是 protected
或者 private
的时候,会报错。你可以将子组件的修饰符更改下尝试。报错的原因如下:
类型 | 使用范围 |
---|---|
public | 允许在累的内外被调用,作用范围最广 |
protected | 允许在类内以及继承的子类中使用,作用范围适中 |
private | 允许在类内部中使用,作用范围最窄 |
4. 通过 service 去变动
我们结合 rxjs
来演示。
rxjs 是使用 Observables
的响应式编程的库,它使编写异步或基于回调的代码更容易。
后期会有一篇文章记录
rxjs
,敬请期待
我们先来创建一个名为 parent-and-child
的服务。
// parent-and-child.service.ts import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; // BehaviorSubject 有实时的作用,获取最新值 @Injectable({ providedIn: 'root' }) export class ParentAndChildService { private subject$: BehaviorSubject<any> = new BehaviorSubject(null) constructor() { } // 将其变成可观察 getMessage(): Observable<any> { return this.subject$.asObservable() } setMessage(msg: string) { this.subject$.next(msg); } }
接着,我们在父子组件中引用,它们的信息是共享的。
// parent.component.ts import { Component, OnDestroy, OnInit } from '@angular/core'; // 引入服务 import { ParentAndChildService } from 'src/app/services/parent-and-child.service'; import { Subject } from 'rxjs' import { takeUntil } from 'rxjs/operators' @Component({ selector: 'app-communicate', templateUrl: './communicate.component.html', styleUrls: ['./communicate.component.scss'] }) export class CommunicateComponent implements OnInit, OnDestroy { unsubscribe$: Subject<boolean> = new Subject(); constructor( private readonly parentAndChildService: ParentAndChildService ) { } ngOnInit(): void { this.parentAndChildService.getMessage() .pipe( takeUntil(this.unsubscribe$) ) .subscribe({ next: (msg: any) => { console.log('Parent: ' + msg); // 刚进来打印 Parent: null // 一秒后打印 Parent: Jimmy } }); setTimeout(() => { this.parentAndChildService.setMessage('Jimmy'); }, 1000) } ngOnDestroy() { // 取消订阅 this.unsubscribe$.next(true); this.unsubscribe$.complete(); } }
import { Component, OnInit } from '@angular/core'; import { ParentAndChildService } from 'src/app/services/parent-and-child.service'; @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.scss'] }) export class ChildComponent implements OnInit { constructor( private parentAndChildService: ParentAndChildService ) { } // 为了更好理解,这里我移除了父组件的 Subject ngOnInit(): void { this.parentAndChildService.getMessage() .subscribe({ next: (msg: any) => { console.log('Child: '+msg); // 刚进来打印 Child: null // 一秒后打印 Child: Jimmy } }) } }
在父组件中,我们一秒钟之后更改值。所以在父子组件中,一进来就会打印 msg
的初始值 null
,然后过了一秒钟之后,就会打印更改的值 Jimmy
。同理,如果你在子组件中对服务的信息,在子组件打印相关的值的同时,在父组件也会打印。
【完】
更多编程相关知识,请访问:编程入门!!
以上就是聊聊Angular中组件之间怎么通信的详细内容,更多请关注站长家园其它相关文章!
本文标签: Angular
转载请注明来源:聊聊Angular中组件之间怎么通信
本文永久链接地址:https://www.adminjie.com/post/11586.html
免责声明:
本站所发布的一切资源仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。本站信息来自网络,版权争议与本站无关。您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。
附:
二○○二年一月一日《计算机软件保护条例》第十七条规定:为了学习和研究软件内含的设计思想和原理,通过安装、显示、传输或者存储软件等方式使用软件的,可以不经软件著作权人许可,不向其支付报酬!鉴于此,也希望大家按此说明研究软件!
版权声明:
一、本站致力于为软件爱好者提供国内外软件开发技术和软件共享,着力为用户提供优资资源。
二、本站提供的部分源码下载文件为网络共享资源,请于下载后的24小时内删除。如需体验更多乐趣,还请支持正版。
三、我站提供用户下载的所有内容均转自互联网。如有内容侵犯您的版权或其他利益的,若有侵犯你的权益请:提交版权证明文件到邮箱 2225329873#qq.com(#换为@) 站长会进行审查之后,情况属实的会在三个工作日内为您删除。
更多精彩内容
- VUE中V-IF条件判断改变元素的样式操作
- Discuz如何解决安装时报错run_sql_error
- 低版本VS项目在VS2019无法正常编译的问题
- PHP+Redis链表解决高并发下商品超卖问题(实现原理及步骤)
- Oracle数据库的实例/表空间/用户/表之间关系简单讲解
- RSA2是啥?PHP-RSA2签名验证怎么实现?
- 华为dubal20是什么型号
- ana an00华为是什么型号
- html5的标题标记一共有几个等级
- 电脑显示信号线无连接是什么意思
- app是什么应用程序的简称
- html5中onclick是什么意思
- vivov1818a是什么手机型号
- 超链接的作用是什么
- 小程序大小超限除了分包还能怎么做?如何避免和解决大小限制?

- 最新文章
-
-
linux中什么是静态路由
在linux中,静态路由是路由项由手动设置的一种路由方式;即使网络状态已经改变或重新被组态,静态路由也是固定不变的,静态路由由网络管理员逐项加入路由表,可用“r...
-
php数组相加会合并重复值么
php数组相加不会合并重复值。php中可使用“+”运算符将一个或多个数组相加起来,会合并这些数组返回一个新数组,语法“数组1+数组2+..”,后面数组的元素会追...
-
php怎么去掉数组前一个元素
方法:1、用“array_values($arr)”将数组转为索引数组;2、用“array_search(值,数组)”从索引数组中搜索值,并返回对应索引;2、用...
-
浅析nodejs项目中的package.json的常见配置属性
本篇文章带大家了解一下node项目中的package.json配置文件,聊聊package.json中一些常见配置属性、环境相关属性、依赖相关属性和三方属性,希...
-
聊聊如何利用uniapp开发一个贪吃蛇小游戏!
如何利用uniapp开发一个贪吃蛇小游戏?下面本篇文章就手把手带大家在uniapp中实现贪吃蛇小游戏,希望对大家有所帮助!第一次玩贪吃蛇还隐约记得是?️后父亲给...
-
- 热门文章
-
-
VUE中V-IF条件判断改变元素的样式操作
这篇文章主要介绍了VUE中V-IF条件判断改变元素的样式操作,具有很好的参考价值,希望对大家有所帮助。一起跟随想过来看看吧...
-
Discuz如何解决安装时报错run_sql_error
问题环境VMware虚拟机Centos7.3PHP7.0MySQL8.0NGINX1.14Discuz3.4问题还原本地环境为PHP5.6+MySQL5.6在安...
-
低版本VS项目在VS2019无法正常编译的问题
低版本VS项目在VS2019无法正常编译的问题这里指的编译并不准确,只是为了方便说明。后有(未安装),201?...
-
PHP+Redis链表解决高并发下商品超卖问题(实现原理及步骤)
实现原理使用redis链表来做,因为pop操作是原子的,即使有很多用户同时到达,也是依次执行,推荐使用。实现步骤第一步,先将商品库存入队列/**.trigge...
-
Oracle数据库的实例/表空间/用户/表之间关系简单讲解
完整的Oracle数据库通常由两部分组成:Oracle数据库和数据库实例。Oracle是一种数据库管理系统,是一种关系型的数据库管理系统。我们用这些高级权限账号...
-