feat: add notifier service
This commit is contained in:
27
src/app/services/notifier.spec.ts
Normal file
27
src/app/services/notifier.spec.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { fakeAsync, TestBed, tick } from '@angular/core/testing';
|
||||
|
||||
import { Notifier } from './notifier';
|
||||
import { Notification } from '../models/Notification';
|
||||
|
||||
describe('Notifier', () => {
|
||||
let service: Notifier;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({});
|
||||
service = TestBed.inject(Notifier);
|
||||
});
|
||||
|
||||
it('should be created', () => {
|
||||
expect(service).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should set notification on notify and clean it after 800ms', fakeAsync(() => {
|
||||
TestBed.tick();
|
||||
const NOTIFICATION_MOCK = new Notification('MOCK NOTIFICATION');
|
||||
service.notify(NOTIFICATION_MOCK);
|
||||
expect(service.notification$()).toEqual(NOTIFICATION_MOCK);
|
||||
TestBed.tick();
|
||||
tick(1000);
|
||||
expect(service.notification$()).toEqual(null);
|
||||
}));
|
||||
});
|
||||
25
src/app/services/notifier.ts
Normal file
25
src/app/services/notifier.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { effect, Injectable, signal } from '@angular/core';
|
||||
import { Notification } from '../models/Notification';
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class Notifier {
|
||||
private readonly notification = signal<Notification | null>(null);
|
||||
readonly notification$ = this.notification.asReadonly();
|
||||
constructor() {
|
||||
effect(() => {
|
||||
if (this.notification$()) {
|
||||
setTimeout(() => {
|
||||
this.cleanup();
|
||||
}, 800);
|
||||
}
|
||||
});
|
||||
}
|
||||
notify(notification: Notification) {
|
||||
this.notification.set(notification);
|
||||
}
|
||||
|
||||
private cleanup() {
|
||||
this.notification.set(null);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user