百分百源码网-让建站变得如此简单! 登录 注册 签到领金币!

主页 | 如何升级VIP | TAG标签

当前位置: 主页>网站教程>JS教程> 5种Angular中组件通讯的办法介绍
分享文章到:

5种Angular中组件通讯的办法介绍

发布时间:09/01 来源:未知 浏览: 关键词:

父子组件通讯

关键词 Input Output EventEmitter ViewChild

1、父组件 向 子组件 传递数据

【Input】

绑定属性的方式

父组件:

<!-- parentComponent -->
<app-child [name]="'childName'"></app-child>

子组件:
// 子组件需要使用Input接收

<span>{{name}}</span>
@Input() public name:string = '';

2、子组件 向 父组件 传递数据

【Output EventEmitter】

子组件:

@Output()
public readonly childEmit: EventEmitter<T> = new EventEmitter<T>();

this.childEmit.emit(data);

父组件:

<app-child (childEmit)="getData($event)"></app-child>
public getData(data:T): void {  }

3、ViewChild 办法

由于我觉得这个办法既可以让父组件猎取子组件的数据,又可以让父组件给子组件设定变量值等,所以我这里独自分了出来。

父组件:

<app-child **#child**></app-child>

<button (click)="**child**.print('---')">点击</button>
@ViewChild('child', { static: true })
public child!: ElementRef<HTMLElement>;

public print():void{
     if(this.child){
       // 这里得到child,可以使用child中的所有的public属性办法
       this.child.print('hello2');
     }
}

【示例】

// 父组件
import { Component } from '@angular/core';

@Component({
  selector: 'app-parent',
  template: `
    <app-child #child [name]="name" (childEmit)="childClick($event)"></app-child>
    <button (click)="child.print('hello1')">调取子组件的办法1</button>
    <button (click)="print()">调取子组件的办法2</button>
  `
})

export class ParentComponent {

   public name:string = '大儿子';
   @ViewChild('child', { static: true })
   public child!: ElementRef<HTMLElement>;

   public childClick(bool:Boolean):void{
      // TODO
   }

   public print():void{
      if(this.child){
        this.child.print('hello2');
     }
   }
}
/*****************************************************/
// 子组件

import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `
    <h3 (click)="myClick()">{{name}}</h3>
  `
})

export class HeroChildComponent {
  @Input() 
  public name: string;

  @Output()
  public readonly childEmit: EventEmitter<boolean> = new EventEmitter<boolean>();

  public myClick():void{
    this.childEmit.emit(true);
  }

  public print(content:string):void{
    console.log(content);
  }
}

非父子组件通讯

1、Service

单例模式,其实就是一个变量,需要双向触发(发送信息 / 接收信息),及设定和猎取数据都需要组件本人去处置。

service.ts

import { Component, Injectable, EventEmitter } from '@angular/core';

@Injectable()

export class myService {
  public info: string = '';
}

组件 1 向 service 传递信息

import { Service1 } from '../../service/service1.service';
...

public constructor(
  public service: Service1,
) { }

public changeInfo():void {
  this.service.info = this.service.info + '1234';
}
...

组件 2 从 service 猎取信息

import { Service2 } from '../../service/service2.service';
...

public constructor(
  public service: Service2,
) { }

public showInfo() {
  console.log(this.service.info);
}
...

2、Subject(公布订阅)

真正的公布订阅模式,当数据改动时,订阅者也能得到响应,这里只举了BehaviorSubject的例子

// Service
import { BehaviorSubject } from 'rxjs';
...
public messageSource = new BehaviorSubject<string>('Start');
public changeMessage(message: string): void {
  this.messageSource.next(message);
}

public getMessageSource(): Observable<string> {
  return this.messageSource.asObservable();
}

/////////////////////////
// 公布
...
this.messageService.changeMessage('message change');
/////////////////////////
public 
// 订阅 (记得按照需要选中可否取消订阅 unsubscribe)
this.messageService.getMessageSource().subscribe(m => {
  console.log(m);
})

四种主题Subject对照

rxjs subject可否储备数据可否需要初始值何时向订阅者公布数据
Subject及时公布。有新数据就公布
BehaviorSubject是。储备最后一条数据或者初始值及时公布。有新数据就公布
ReplaySubject是。储备所有数据及时公布。有新数据就公布
AsyncSubject是。储备最后一条数据延时公布。只要当数据源complete的时候才会公布

其他通讯方式

路由传值、阅读器当地储备(LocalStorage,SessionStorage)、cookie。

打赏

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

百分百源码网 建议打赏1~10元,土豪随意,感谢您的阅读!

共有151人阅读,期待你的评论!发表评论
昵称: 网址: 验证码: 点击我更换图片
最新评论

本文标签

广告赞助

能出一分力是一分吧!

订阅获得更多模板

本文标签

广告赞助

订阅获得更多模板