import { Component, OnDestroy, ViewChild, OnInit } from '@angular/core'; import { MatSidenav, MatDialog } from '@angular/material'; import { Profile } from '@app/core/models/profile'; import { FormBuilder, FormGroup, FormControl, Validators, } from '@angular/forms'; import { Course } from '@app/core/models/course'; import { WebsocketService, TokenPayload, } from './shared/services/websocket.service'; import { DegreePlannerApiService } from '@app/degree-planner/services/api.service'; import { Store } from '@ngrx/store'; import { GlobalState } from './core/state'; import { Initialize } from './core/actions'; import { Subscription } from 'rxjs'; @Component({ selector: 'cse-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'], providers: [WebsocketService], }) export class AppComponent implements OnInit, OnDestroy { coursesData$: any; selectedDegreePlan: number; courses: Course[]; profile: Profile; coursesForm: FormGroup; subjectCode: FormControl; @ViewChild('rightAddCourse') public rightAddCourse: MatSidenav; connected = false; connectionState = 'Disconnected'; lastMessage: string; jwtToken = ''; subscription: Subscription; messageSubscription: Subscription; constructor( public dialog: MatDialog, private fb: FormBuilder, private api: DegreePlannerApiService, private wsclient: WebsocketService, private store: Store<GlobalState>, ) { this.subjectCode = new FormControl('', [Validators.required]); this.coursesForm = this.fb.group({ coursesInput: null, }); } ngOnInit() { this.store.dispatch(new Initialize()); this.api.getUserProfile().subscribe(profile => { const customEvent = new CustomEvent('myuw-login', { detail: { person: { firstName: profile.firstName, }, }, }); document.dispatchEvent(customEvent); }); this.subscription = this.wsclient.connectionState.subscribe(message => { this.connectionState = message; if (this.connectionState === 'Disconnected!') { this.wsclient.ws.reconnect(); } }); this.messageSubscription = this.wsclient.messages.subscribe(message => { this.lastMessage = message; }); this.getToken(); } getToken() { this.wsclient.getToken().subscribe((token: TokenPayload) => { this.jwtToken = token.token; this.connect(); }); } connect() { const token = this.jwtToken; this.wsclient.connectToServer(token); this.connected = true; this.connectionState = 'Connected'; } disconnect() { this.wsclient.disconnect(); this.connected = false; this.connectionState = 'Disconnected'; } ngOnDestroy() { this.subscription.unsubscribe(); this.messageSubscription.unsubscribe(); } }