import {Component, OnDestroy, OnInit} from '@angular/core'; import {DeviceService} from '../state/device.service'; import {filter, map, startWith, switchMap, tap} from 'rxjs/operators'; import {DeviceQuery} from '../state/device.query'; import {noop, Observable, Subscription} from 'rxjs'; import {Log} from '../state/device.model'; import {animate, state, style, transition, trigger} from '@angular/animations'; import {isNil} from '@datorama/akita'; import {SocketService} from '../../socket.service'; import {eventOfType, EVENTS} from '../../const'; @Component({ selector: 'dia-man-tools-page', templateUrl: './page.component.html', styleUrls: ['./page.component.css'], animations: [ trigger('detailExpand', [ state('collapsed', style({height: '0px', minHeight: '0'})), state('expanded', style({height: '*'})), transition('expanded <=> collapsed', animate('225ms cubic-bezier(0.4, 0.0, 0.2, 1)')) ]) ] }) export class PageComponent implements OnInit, OnDestroy { private readonly subs = new Subscription(); devices$ = this.deviceQuery.selectAll(); logs$: Observable = this.deviceQuery.selectActiveId().pipe( switchMap(id => this.deviceQuery.select('logs').pipe(map(logs => logs[id]))) ); displayedColumns = ['sn', 'ip', 'time']; constructor( private readonly deviceQuery: DeviceQuery, private readonly deviceService: DeviceService, private readonly socketService: SocketService ) { } logs(sn: string) { const hasActive = this.deviceQuery.hasActive(sn); this.deviceService.setActive(hasActive ? null : sn); } get activeId() { return this.deviceQuery.getActiveId(); } delete(sn: string) { this.deviceService.delete(sn).toPromise().then(noop); } ngOnInit(): void { //REGISTER_COMPLETE this.subs.add( this.socketService.socket.pipe( eventOfType( EVENTS.REGISTER_ERROR, EVENTS.FACTORY_RESET_ERROR, EVENTS.CERTIFICATE_ERROR, EVENTS.CONNECTIVITY_TEST_ERROR, EVENTS.SET_CERTIFICATE_ERROR, EVENTS.DEVICE_VALIDATION_ERROR ), startWith(true), switchMap(() => this.deviceService.fetchDevices()) ).subscribe() ); this.subs.add( this.deviceQuery.selectActiveId().pipe( tap(console.log), filter(active => !isNil(active)), switchMap(sn => this.deviceService.fetchLogs(sn)) ).subscribe() ); } ngOnDestroy(): void { this.subs.unsubscribe(); } }