ค้นหาเว็บไซต์

javascript - วิธีติดตามการเปลี่ยนแปลงของค่าที่ส่งออกจากคอมโพเนนต์หนึ่งไปยังคอมโพเนนต์อื่นใน Angular


Component A แสดงจำนวนการแจ้งเตือน ขณะที่ Component B จะรับจำนวนการแจ้งเตือนแบบเรียลไทม์ซึ่งฉันกำลังส่งค่าออกและสมัครรับค่าที่ Component A ด้วย ด้วยเหตุผลบางอย่าง จำนวนจะอัปเดตก็ต่อเมื่อฉันทำการเปลี่ยนหน้า

โดยสรุป นี่คือสิ่งที่ฉันกำลังทำอยู่

ส่วนประกอบ B

ngOnInit(){
 this.handleRealTimeCount();
}

handleRealTimeCount() {
  this.countSvc
    .getCount()
    .subscribe((res: any) => {
      this.countSvc.setCount(
        res.count
      );
    });
}

ส่วนประกอบ A

  this.getUnreadCount();
}

getUnreadCount() {
  this.countSvc.unreadCount.subscribe((res) => {
    this.notificationsCount = res;
  });
}

ใน บริการนับ ของฉัน ฉันกำลังใช้ตัวแปร EventEmitter แบบนี้

export class CountService {
  unreadCount = new EventEmitter();

  setCount(count) {
    this.unreadCount.emit(count);
  }

คุณช่วยบอกฉันได้ไหมว่าฉันจะทำอย่างไรให้จำนวนแบบเรียลไทม์อัปเดตทุกครั้งที่ได้รับการแจ้งเตือน

คำตอบ #1

คุณช่วยลองใช้ BehaviorSubject แทน EventEmitter ได้ไหม

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class CountService  {   
  constructor() { } 
  private paramSource = new BehaviorSubject(0);
  unreadCount = this.paramSource.asObservable();
  setCount(param:number) { this.paramSource.next(param)}    
}

คำตอบ #2

คุณเกือบจะสำเร็จแล้ว ผมขอแนะนำให้ใช้ BehaviourSubject ในบริการแทน EventEmitter และสมัครสมาชิกโดยตรงในเทมเพลตของคอมโพเนนต์ของคุณโดยใช้ async pipe

บริการ

@Injectable({
  providedIn: 'root'
})
export class CountService {
  private _unreadCount$: BehaviourSubject<number> = new BehaviourSubject<number>(0);
  get unreadCount$ ():Observable <number> {
  return this._unreadCount$;
  }

  increaseCount(amount:number) {
  this._unreadCount.pipe(take(1)).subscribe((count: number) => {
  this._unreadCount.next(count + amount);
})

}

ส่วนประกอบ A

count$: Subject<number> = new Subject<number>();

getUnreadCount() {
  this.countSvc.unreadCount$.subscribe((count) => {
    this.count$.next(count);
  });
}

increase(count: number) {
this.countSvc.increaseCount(count);
}

// Template of Component A

<div *ngIf="count$ | async as count">
You have {{count}} notifications
</div>
<button (click)="increase(1)">Increase</button>

พื้นฐานก็คือเท่านั้น โดยการทำตามแนวทางข้างต้น คอมโพเนนต์ของคุณจะซิงค์กัน แค่แน่ใจว่าคุณเติมบริการและสมัครรับ property unreadCount$