聊聊Angular中組件之間怎么通信( 二 )

這種方法有個限制? , 就是子屬性的修飾符需要是 public , 當是 protected 或者 private 的時候 , 會報錯 。 你可以將子組件的修飾符更改下嘗試 。 報錯的原因如下:
類型使用范圍public允許在累的內外被調用 , 作用范圍最廣protected允許在類內以及繼承的子類中使用 , 作用范圍適中private允許在類內部中使用 , 作用范圍最窄4. 通過 service 去變動我們結合 rxjs 來演示 。
rxjs 是使用 Observables 的響應式編程的庫 , 它使編寫異步或基于回調的代碼更容易 。

后期會有一篇文章記錄 rxjs , 敬請期待
我們先來創建一個名為 parent-and-child 的服務 。
// parent-and-child.service.tsimport { 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.tsimport { 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中組件之間怎么通信的詳細內容 , 更多請關注電腦自學網其它相關文章!

推薦閱讀