mirror of
				https://github.com/avatao-content/frontend-tutorial-framework
				synced 2025-11-04 11:52:54 +00:00 
			
		
		
		
	Implement base class for future config services
This commit is contained in:
		
							
								
								
									
										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]);
 | 
			
		||||
      }
 | 
			
		||||
    });
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
		Reference in New Issue
	
	Block a user