[英]How to track change of a value emitted in one component in another component in Angular
Component A
shows notifications count. Component A
显示通知计数。 Whereas, Component B
gets live count of notificationss which I'm emitting it and subscribing the value in Component A
.而
Component B
获得通知的实时计数,我发出它并订阅Component A
中的值。 For some reason, the count gets updated only when I make page transition.出于某种原因,只有在我进行页面转换时才会更新计数。
In a gist, here's what I'm doing.简而言之,这就是我正在做的事情。
Component B B组份
ngOnInit(){
this.handleRealTimeCount();
}
handleRealTimeCount() {
this.countSvc
.getCount()
.subscribe((res: any) => {
this.countSvc.setCount(
res.count
);
});
}
Component A组分 A
this.getUnreadCount();
}
getUnreadCount() {
this.countSvc.unreadCount.subscribe((res) => {
this.notificationsCount = res;
});
}
In my Count Service , I'm using EventEmitter
variables like this在我的Count Service中,我正在使用这样的
EventEmitter
变量
export class CountService {
unreadCount = new EventEmitter();
setCount(count) {
this.unreadCount.emit(count);
}
Could you please let me know how could I get the real time count updated whenever a notification is received.您能否告诉我如何在收到通知时更新实时计数。
Can you try with BehaviorSubject rather than EventEmitter您可以尝试使用 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)}
}
You are almost there.你快到了。 I will suggest using a
BehaviourSubject
in the service rather than an EventEmitter
and also subscribe directly in the template of your components using the async
pipe.我会建议在服务中使用
BehaviourSubject
而不是EventEmitter
,并且还可以使用async
pipe 在组件的模板中直接订阅。
The Service服务
@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);
})
}
Component A组分 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>
Basically that's it.基本上就是这样。 By following the above approach your components will be synced, just make sure to inject the service and subscribe to the unreadCount$ property
按照上述方法,您的组件将被同步,只需确保注入服务并订阅 unreadCount$ 属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.