首頁 > web前端 > js教程 > 主體

5種Angular中組件通訊的方法介紹

青灯夜游
發布: 2021-02-01 11:47:48
轉載
2278 人瀏覽過

5種Angular中組件通訊的方法介紹

元件化是Angular的核心概念,所以元件通訊的使用就比較多而且很重要。

官方傳送門:

##https://angular.io/guide/component-interaction 

https://angular.cn/guide/component- interaction

相關教學推薦:《

angular教學

#父子元件通訊

關鍵字    Input    Output    EventEmitter ViewChild

1、父元件傳遞資料給子元件

【Input】

#綁定屬性的方式


#父元件:

<!-- parentComponent -->
<app-child [name]="&#39;childName&#39;"></app-child>
登入後複製

子元件:

// 子元件需要使用Input接收

<span>{{name}}</span>
登入後複製
@Input() public name:string = &#39;&#39;;
登入後複製

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(&#39;---&#39;)">点击</button>
登入後複製
@ViewChild(&#39;child&#39;, { static: true })
public child!: ElementRef<HTMLElement>;

public print():void{
     if(this.child){
       // 这里得到child,可以使用child中的所有的public属性方法
       this.child.print(&#39;hello2&#39;);
     }
}
登入後複製

【範例】

// 父组件
import { Component } from &#39;@angular/core&#39;;

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

export class ParentComponent {

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

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

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

import { Component, Input, Output, EventEmitter } from &#39;@angular/core&#39;;

@Component({
  selector: &#39;app-child&#39;,
  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 &#39;@angular/core&#39;;

@Injectable()

export class myService {
  public info: string = &#39;&#39;;
}
登入後複製
元件1 向service 傳遞訊息
import { Service1 } from &#39;../../service/service1.service&#39;;
...

public constructor(
  public service: Service1,
) { }

public changeInfo():void {
  this.service.info = this.service.info + &#39;1234&#39;;
}
...
登入後複製
import { Service2 } from &#39;../../service/service2.service&#39;;
...

public constructor(
  public service: Service2,
) { }

public showInfo() {
  console.log(this.service.info);
}
...
登入後複製
2、Subject(發布訂閱)
// Service
import { BehaviorSubject } from &#39;rxjs&#39;;
...
public messageSource = new BehaviorSubject<string>(&#39;Start&#39;);
public changeMessage(message: string): void {
  this.messageSource.next(message);
}

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

/////////////////////////
// 发布
...
this.messageService.changeMessage(&#39;message change&#39;);
/////////////////////////
public 
// 订阅 (记得根据需要选择是否取消订阅 unsubscribe)
this.messageService.getMessageSource().subscribe(m => {
  console.log(m);
})
登入後複製
四種主題Subject對比rxjs subject是否儲存資料是否需要初始值何時向訂閱者發布資料Subject##否及時發布。有新資料就發布BehaviorSubject是。儲存最後一條資料或初始值是及時發布。有新資料就發布ReplaySubject是。儲存所有資料否及時發布。有新資料就發布

AsyncSubject

是。儲存最後一條資料

延時發布。只有當資料來源complete的時候才會發布###############其他通訊方式######路由傳值、瀏覽器本地儲存(LocalStorage,SessionStorage)、cookie。 ######更多程式相關知識,可存取:###程式設計入門###! ! ######

以上是5種Angular中組件通訊的方法介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:jianshu.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!
元件2 從service 取得資訊真正的發布訂閱模式,當資料改變時,訂閱者也能得到回應,這裡只舉了BehaviorSubject的例子