我正在为Angular应用程序设置通知功能。
标题中:
登录后,标头仅调用一次,我有一个带有未读通知数量的徽章:
<button mat-icon-button>
<mat-icon matBadge="{{unreadNotifications}}" matBadgeColor="red" matBadgeOverlap="true" matBadgePosition="below after">
notifications
</mat-icon>
</button>
还有我的控制器:
notificationSub: Subscription;
ngOnInit() {
this.notificationSub = this.notifService.getAsyncNotifsCount().subscribe((res) => {
this.unreadNotifications = res;
});
}
通知可以显示在通知页面中:
<div *ngFor="let notif of notifsBeforeRead" class="notif">
<div class="notif-title">{{ notif.Subject }}</div>
<div>{{ notif.Message }}</div>
<div class="notif-date">{{ notif.Date | date : 'medium' }}</div>
</div>
还有我的控制器:
notificationSub: Subscription;
this.notifService.apply({ collectionName: 'Links' }, myFilter);
this.notificationSub = this.notifService.getAsyncFilter()
.subscribe((links) => {
if (links.data && links.data.length) {
// this.resultsLength = links.options.documents.total;
this.resultsLength = 20;
Array.prototype.forEach.call(links.data, (link) => {
const notif = {};
link.attributes.forEach((attr) => {
notif['id'] = link._id;
notif['attributes'] = link.attributes;
link.attributes.forEach((att) => {
notif[att.name] = att.value;
});
});
if (Object.keys(notif).length) {
notifications.push(notif);
}
});
}
this.notifsBeforeRead = notifications;
this.notifications = _.cloneDeep(notifications);
// Mark notifications as read
this.updateReadNotif();
});
和我的 notifService :
@Injectable()
export class NotifService {
filterSubject = new Subject<any>();
notifsCountSubject = new BehaviorSubject<any>(0);
apply(params = null, filter: any) {
const _resource = this.resource;
let targetURL = `${this.resourceApply}`;
if (params) {
targetURL += `?${queryParams(params)}`;
}
this.getData(targetURL, filter).subscribe((res) => {
this.filterSubject.next(res);
console.log(res.data);
let unreadNotifs = 0;
res.data.forEach((notif) => {
notif.attributes.forEach((attr) => {
if (attr.name === 'Lu' && attr.value === false) {
unreadNotifs += 1;
}
});
});
this.notifsCountSubject.next(unreadNotifs);
});
}
getData(targetURL, filter) {
this.resource = targetURL;
return from(super.create(filter));
}
getAsyncFilter() : Observable<any> {
return this.filterSubject.asObservable();
}
getAsyncNotifsCount(): Observable<any> {
return this.notifsCountSubject.asObservable();
}
}
代码不是全部,但我想您只能为此提供帮助。
因此,当我进入通知页面时,徽章不会更新。
例如:我有5条未读通知。
我进入通知页面,因此我输入了以下代码:
this.notifsCountSubject.next(unreadNotifs); // unreadNotifs = 0
但是标头中的徽章未更新。我已经订阅了该主题,当我使用.next()时,所有订阅者都应该更新其数据,对吗?
能帮我吗,谢谢。
答案 0 :(得分:1)
我们发现,问题在于它是2个不同的服务实例,因为它在模块的提供者和组件的提供者中,因此组件每次都获得新的服务实例。