我有一个组件应该显示未读通知的数量,并且此值作为 unread
存储在我的服务中。
@Injectable({
providedIn: 'root'
})
export class NotificationService implements OnDestroy {
base_url: string;
auth_token: string;
headers: HttpHeaders;
private notifications = new BehaviorSubject<Notification[]>([])
notifications$ = this.notifications.asObservable()
private unread = new BehaviorSubject<Notification[]>([])
unread$ = this.unread.asObservable()
unreadSubscription: Subscription;
private read = new BehaviorSubject<Notification[]>([])
read$ = this.read.asObservable()
constructor(private global: GlobalsService,
private http: HttpClient,
private storage: Storage,
private auth: AuthService ) {
this.base_url = this.global.base_url;
}
ngOnDestroy() {
if (this.unreadSubscription) this.unreadSubscription.unsubscribe()
}
setNotifications(notifications : Notification[]) {
console.log("setNotifications", notifications)
this.notifications.next(notifications)
this.storage.set('notifications', notifications)
let arr = _.filter(notifications, { read_at: null })
this.unread.next(arr)
}
}
在我看来,我显示未读通知的数量:
client-detail.page.html
<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-back-button (click)="goBack()" defaultHref="clients">
</ion-back-button>
</ion-buttons>
<ion-title>Title</ion-title>
<ion-buttons slot="end">
<logout-component></logout-component>
</ion-buttons>
</ion-toolbar>
</ion-header>
logout.component
<span>
<ion-button (click)="signOut()">
<ion-icon name="person" style="font-size:32px;"></ion-icon>
<span class="ion-padding-start" style="vertical-align: super;">{{email}}</span>
</ion-button>
<ion-badge *ngIf="( notificationsService.unread$ | async ).length > 0">
{{ ( notificationsService.unread$ | async ).length }}
</ion-badge>
</span>
export class LogoutComponent implements OnDestroy, OnChanges {
@Input() color: string;
@Output() showHelp: EventEmitter<any> = new EventEmitter();
@Output() hideHelp: EventEmitter<any> = new EventEmitter();
currentUserSubscription: Subscription;
notificationsSubscription: Subscription;
constructor(private storage: Storage,
private actionSheetCtrl: ActionSheetController,
private clientService: ClientService,
private globalService: GlobalsService,
private navCtrl: NavController,
private modalCtrl: ModalController,
private notificationsService: NotificationService,
public auth: AuthService,
private router: Router) {
}
}
出于某种原因,即使在调用 NotificationService.setNotifications()
并看到通知和未读通知正在更新并且可以显示之后,当我检查 NotificationService
时在 LogoutComponent
中,notifications$
和 unread$
的值保持不变。这几乎就像 LogoutComponent
将 NotificationService
视为单例一样。
可能值得注意的是,LogoutComponent
和 NotificationService
位于不同的模块中,但两者都应该出现在 AppModule
中。
最佳答案
尽管调用了 providedIn: 'root'
,该服务也被导入到另一个模块中。从该模块中删除服务后,一切都按预期工作。
关于angular - 尽管在 root 中提供了多个版本的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66359472/