服务组件之间的通信不起作用

Communication between components by service not working

我正在使用 BehaviorSubject class 来更新我全局中的通知数量。 我有 2 个组件:组件通知显示通知列表,您可以将这些通知设置为已读。 header 组件显示未阅读的通知数量,让用户知道他错过了网站上的某些内容。 由于有 2 个不同的组件,我使用服务通过它们进行通信。

这里是一些片段:

notification.service.ts

export class NotificationService {
     public notification: BehaviorSubject<Object> = new BehaviorSubject<Object>({});
     public nbNotificationsChange: BehaviorSubject<number>;

constructor(){
     this.nbNotificationsChange = new BehaviorSubject<number>(0);
}

updateNbNotification(value) {
    this.nbNotificationsChange.next(value);
    this.nbNotificationsChange.subscribe(x => console.log(x));
}

getNbNotification(){
    return this.nbNotificationsChange.getValue();
} }

header.component.ts

export class HeaderComponent implements OnInit, DoCheck {
    public notifications: Notification[] = [];
    public nbNotifications: number = 0;


    constructor (public notificationService: NotificationService){
    this.notificationService.nbNotificationsChange.subscribe(value => {
            this.nbNotifications = value;
        });
    }
ngOnInit() {
    this.getNotificationsNotRead();
    this.notificationService.nbNotificationsChange.subscribe(value => {
        this.nbNotifications = value;
    });
}

ngDoCheck(){
    this.nbNotifications = this.notificationService.getNbNotification()
    //console.log("test");
}
getNotificationsNotRead(){
    aNotRelevantFunctionToRetreiveNotification.subscribe(
            this.notifications = //Receive an array of Notifications here with some code
            this.notifications = this.notifications.filter((notif : Notification) => notif.seen == false); // Check if a notification is read or not
            this.notificationService.updateNbNotification(this.notifications.length);
            console.log(this.notifications.length);
    );
}

get nbNotif(): number {
    return this.notificationService.getNbNotification();
} }

notification.component.ts

export class NotificationsComponent implements OnInit {

public notifications: Notification[];

constructor(public notificationService: NotificationService) {}

ngOnInit() {
    this.getAllNotifications();
}

public getAllNotifications() {
    //Receive an array of notifications to display them, passsing this code. We're in the subscribe
    var nbNotifNotRead = this.notifications.filter((notif : Notification) => notif.seen == false).length;
    this.notificationService.updateNbNotification(nbNotifNotRead); //This value is properly set
}
}

问题是,即使在notification.component.ts端设置值,在header.component.ts中检索到的值也不是好的,是初始值,不是什么我当然要

有人有想法吗?现在已经为此苦苦挣扎了太多时间


更新

这是html部分,非常简单:

<span class="SomeCSSClasses" *ngIf="nbNotifications > 0">{{nbNotifications}}</span>

更新 2

涉及的模块:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpModule } from '@angular/http';
/* A lot of imports */

@NgModule({
  imports: [
    CommonModule,
    HttpModule,

  ],
  providers: [
    ApiService,
    CurrencyService,
    /* A lot of services */
    NbNotificationService
    ]
})

export class ServicesModule { }

这是在 App.module 中导入的原始模块。 我通过这样创建自己的模块:

import { ModuleWithProviders, NgModule, Optional, SkipSelf } from '@angular/core';

import { NbNotificationService } from './nb-notification.service';
@NgModule({
  providers:    [ NbNotificationService ]
})

export class NbNotificationServiceModule {
    constructor (@Optional() @SkipSelf() parentModule: NbNotificationServiceModule) {
        if (parentModule) {
          throw new Error(
            'NbNotificationServiceModule is already loaded. Import it in the AppModule only');
        }
      }

    static forRoot(): ModuleWithProviders {
        return {
          ngModule: NbNotificationServiceModule,
          providers: [
            {provide: NbNotificationService, useValue: 0 }
          ]
        };
      }
}

试图将其添加到 AppModule,但出现如下错误:Cannot instantiate cyclic dependency! NbNotificationService ("[ERROR ->]"): in NgModule PagesModule in ./PagesModule@-1:-1

既然您的服务中有通知,为什么不简单地使用 getter 呢?

notification.service.ts

notifications: Notification[];

header.component.ts

get totalNotifications() { return this.notificationService.notifications.length; }

如果您的服务在 lazy-loaded 模块中提供并且您想要一个 application-wide 单例,则需要实现 .forRoot() 并在那里提供服务并在 [=] 中导入模块11=] 与 MyModule.forRoot

由于 DI 上下文在创建后无法修改,延迟加载的模块会为其提供程序获取新的上下文,并且只有该模块和作为其一部分加载的其他模块才能看到相同的提供程序实例。 AppModule、non-lazy 加载的模块和其他 lazy-loaded 模块将不会获得实例或获得不同的实例。

另见 https://angular.io/guide/singleton-services#forroot