mirror of
https://github.com/avatao-content/frontend-tutorial-framework
synced 2024-12-05 02:21:31 +00:00
Implement base class for future config services
This commit is contained in:
parent
65c7c727f5
commit
41eebc60f6
53
src/app/services/config.service.base.ts
Normal file
53
src/app/services/config.service.base.ts
Normal file
@ -0,0 +1,53 @@
|
|||||||
|
import { Injectable } from '@angular/core';
|
||||||
|
import { WebSocketService } from './websocket.service';
|
||||||
|
import { Subject, BehaviorSubject, forkJoin } from 'rxjs';
|
||||||
|
import { take } from 'rxjs/operators';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export abstract class ConfigServiceBase {
|
||||||
|
initDone = false;
|
||||||
|
keys = new Array<string>();
|
||||||
|
mandatoryConfigs = new Array<any>();
|
||||||
|
configDone = new Subject<void>();
|
||||||
|
|
||||||
|
constructor(private webSocketService: WebSocketService) {}
|
||||||
|
|
||||||
|
init() {
|
||||||
|
if (this.initDone) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.waitForMandatoryConfigs();
|
||||||
|
this.subscribeConfigKeys();
|
||||||
|
this.initDone = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
waitForMandatoryConfigs() {
|
||||||
|
const firstConfigs = new Array<any>();
|
||||||
|
this.mandatoryConfigs.forEach((config) => {
|
||||||
|
const requiredEmitCount = config instanceof BehaviorSubject ? 2 : 1;
|
||||||
|
firstConfigs.push(config.pipe(take(requiredEmitCount)));
|
||||||
|
});
|
||||||
|
|
||||||
|
forkJoin(firstConfigs).subscribe(undefined, undefined, () => {
|
||||||
|
this.configDone.next();
|
||||||
|
this.configDone.complete();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
subscribeConfigKeys() {
|
||||||
|
this.webSocketService.connect();
|
||||||
|
this.keys.forEach(key =>
|
||||||
|
this.webSocketService.observeKey<any>(key).subscribe(this.handleConfig.bind(this))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
handleConfig(message: any) {
|
||||||
|
Object.keys(message).filter(key => key !== 'key').forEach(key => {
|
||||||
|
if (this[key] === undefined) {
|
||||||
|
console.log(`Invalid ${this.keys} config key "${key}"!`);
|
||||||
|
} else {
|
||||||
|
this[key].next(message[key]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user