how to filter the list of objects and stop a service request in case of duplicate records/object by using angular 14.2.6?

45 views
Skip to first unread message

0ma...@gmail.com

unread,
Feb 25, 2023, 3:00:38 PM2/25/23
to Angular and AngularJS discussion

I have an application with two angular 14 components. One is parent and the other is child component.

Parent component have an array of objects while child component add the objects by fetching from a service method. Now I need to stop duplication and service calls if a certain code is repeated/duplicated in a list of object.

For example

export class MedicationPermissionModel { Id:number; ProviderSpi: string; canProviderCancelRx:boolean = false; canPharmacyCancel: boolean = false; endDateHasPassed: boolean = false; isChronicMedication: boolean = false; isMedicationEprescribed:boolean = false; showCancelRxCheckBox:boolean = false; }

this is the parent component

import { Component, ElementRef, Inject, OnInit, QueryList, Renderer2, ViewChildren } from '@angular/core'; import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { ActivatedRoute } from '@angular/router'; import { ToLowerParam } from '../../../../../../../cure-client-lib/src/shared/constants/param- constants'; import { MedicationsFacesheetPopupComponent } from '../medications-facesheet-popup/medications- facesheet-popup.component'; import { PrescriptionFacesheetService } from '../../services/prescription-facesheet.service'; import { MedicationModel } from '../../../medication/models/medication/Medication.Model'; import { TreatmentPlanStateService } from '../../../treatment-plan/services/treatmentplan-state.service'; import { TreatmentPlanFacade } from '../../../treatment-plan/services/treatmentplan- facade.service'; import { TreatmentPlan } from '../../../treatment-plan/models/treatment-plan.model'; import { OrderingComponent } from 'projects/cure-client-app/src/app/shared/enums/ordering-component.enum'; import { MedicationService } from '../../../medication/services/medication/Medication.Service'; import { Subscription } from 'rxjs'; import * as MedicationHelper from '../../../medication/utilities/medication-helper.util'; import { MdePopoverTrigger } from '@material-extended/mde'; import { NotifierService } from 'projects/cure-client-lib/src/shared/services/notifier.service'; import { LocalizationService } from 'projects/cure-client-lib/src/shared/services/localization.service'; import { MedicationPermissionModel } from '../../models/medication-permission.model'; import { PrescriptionService } from '../../../medication/services/prescription/prescription.service'; @Component({ selector: 'app-medications-facesheet-tile', templateUrl: './medications-facesheet-tile.component.html', }) export class MedicationsFacesheetTileComponent implements OnInit { medicationList: MedicationModel[] = []; pastMedicationList: MedicationModel[] = []; patientId: number; treatmentPlan: TreatmentPlan = {} as TreatmentPlan; subscription: Subscription; saveCallMedicationsUpdated: boolean = false; spiPerList : MedicationPermissionModel[] = []; @ViewChildren('matMedicationButtonRef', { read: ElementRef }) matButtons: QueryList<ElementRef>; @ViewChildren(MdePopoverTrigger) trigger: QueryList<MdePopoverTrigger>; showActionButtons: boolean = true; constructor( private route: ActivatedRoute, private localizatonService: LocalizationService, private dialog: MatDialog, private dialogRef: MatDialogRef<MedicationsFacesheetPopupComponent>, @Inject(MAT_DIALOG_DATA) public data: any, private prescriptionService: PrescriptionFacesheetService, private treatmentPlanStateService: TreatmentPlanStateService, private treatmentPlanService: TreatmentPlanFacade, private medicationService: MedicationService, private _renderer: Renderer2, private notifierService: NotifierService, private presService : PrescriptionService, ) { this.subscription = new Subscription(); } ngOnInit(): void { this.subscribeForTreatmentPlan() this.route.queryParams.subscribe((params) => { const _params = ToLowerParam(params); if (_params['patientid'] && _params['patientid'] > 0) { this.patientId = Number(_params['patientid']); } else { return; } this.getAlreadyPrescribedMedications(); this.getPastMedications(); }); this.localizatonService.setLocalizationSettingsFromStore(); this.subscription.add( this.presService.surescriptProviderMedPerListObserver.subscribe( (obj:any) =>{ if(obj) { this.spiPerList.push(obj); //this.presService.setSureScriptProviderMedPerList(null); } } ) ); } private subscribeForTreatmentPlan() { this.treatmentPlanStateService.getTreatmentPlanObject().subscribe((treatmentPlanObj: any) => { if (treatmentPlanObj) { this.treatmentPlan = treatmentPlanObj; if(this.treatmentPlan.State === 3 ){ this.saveCallMedicationsUpdated = true if(this.saveCallMedicationsUpdated){ this.getAlreadyPrescribedMedications(); this.getPastMedications(); } } if(this.treatmentPlan.State >= 2){ this.showActionButtons = false } else{ this.showActionButtons = true } } } ); } getContainerDiagnosisByCode(code: string): any { return this.treatmentPlan.TreatmentPlanDiagnoses.find((x) => x.Code === code); } async onSelectDiagnosis(event: any, medication: MedicationModel) { let selectedDiagnoses: string[] = event.selectedDiagnosisCodes selectedDiagnoses.forEach(element => { this.treatmentPlanService.addContainerComponent(OrderingComponent[OrderingComponent.Medication], medication, this.getContainerDiagnosisByCode(element).DiagnosisClientIndex); }); } GetTodayDate() { var tdate = new Date(); var dd = tdate.getDate(); //yields day var MM = tdate.getMonth(); //yields month var yyyy = tdate.getFullYear(); //yields year var xxx = (MM + 1) + "/" + dd + "/" + yyyy; return xxx; } private async getAlreadyPrescribedMedications() { let medicationList = await this.prescriptionService.getAlreadyPrescribedMedications(this.patientId); if (medicationList && medicationList.Content) { this.medicationList = medicationList.Content; } } private async getPastMedications() { let medicationList = await this.prescriptionService.getPastMedications(this.patientId); if (medicationList && medicationList.Content) { this.pastMedicationList = medicationList.Content; } } onMedicationsListExpanded() { this.logger.info("Medications Facesheet expanded.") this.dialog .open(MedicationsFacesheetPopupComponent, { width: '1200px', data: { medicationList: this.medicationList, pastMedicationList: this.pastMedicationList, }, }) .afterClosed() .subscribe((result) => { this.logger.info('Medication Facesheet closed'); if (result && result.event === 'submit') { this.dialogRef.close({ event: 'submit' }); } }); } onMedicationPerMissionList(event : any){ if(event.medicationPermission){ this.spiPerList.push(event.medicationPermission); } } getMedicationDirections(medication : MedicationModel){ return MedicationHelper.getMedicationDirections(medication) } }

and this is the child component

import { Component, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core'; import { UntypedFormBuilder } from '@angular/forms'; import { MatDialog } from '@angular/material/dialog'; import { ResponseData } from 'projects/cure-client-lib/src/shared/models/response-data.model'; import { Observable, Subscription } from 'rxjs'; import { map } from 'rxjs/operators'; import { MedicationModel } from '../../../medication/models/medication/Medication.Model'; import { PharmacyView } from '../../../medication/models/pharmacy/pharmacy.model'; import { Address } from '../../../medication/models/prescription/Address.model'; import { ProviderModel, Type } from '../../../medication/models/prescription/provider.model'; import { DiscontinueMedicationPopupComponent } from '../../../medication/popups/discontinue- medication-popup/discontinue-medication-popup.component'; import { MedicationService } from '../../../medication/services/medication/Medication.Service'; import * as StringFormatter from '../../../medication/utilities/string-formatter.util' import * as PhoneFormatter from '../../../medication/utilities/phone-formatter.util' import { PrescriptionService } from '../../../medication/services/prescription/prescription.service'; import { MdePopoverTrigger } from '@material-extended/mde'; import { TreatmentPlanStateService } from '../../../treatment-plan/services/treatmentplan- state.service'; import { TreatmentPlan } from '../../../treatment-plan/models/treatment-plan.model'; import { select, Store } from '@ngrx/store'; import { StartupInfo } from 'projects/cure-client-lib/src/shared/models/startup-info.model'; import { MedicationPermissionModel } from '../../models/medication-permission.model'; import { MedicationApiGenericResponse } from '../../../medication/models/medication/medication- api-generic-response.model'; @Component({ selector: 'app-medication-actions', templateUrl: './medication-actions.component.html' }) export class MedicationActionsComponent implements OnInit { @ViewChild(MdePopoverTrigger, { static: false }) trigger: MdePopoverTrigger; @Input() medication : MedicationModel @Output() discontinuedMedication : EventEmitter<{Message : string, medication : MedicationModel}> = new EventEmitter<{Message : string, medication : MedicationModel}>() @Input() spiPerList : MedicationPermissionModel[] @Output() medicationPerMissionList : EventEmitter<{medicationPermission : MedicationPermissionModel}> = new EventEmitter<{medicationPermission : MedicationPermissionModel}>() discontinueReason: string = '' discontinueDescription: string = '' subscription : Subscription medicationProvider : ProviderModel medicationActionForm = this.fb.group({ cancelRxSendCheck : true, discontinueReason : null, discontinueDescription : null }) canProviderCancelRx: boolean = false; canPharmacyCancel: boolean = false; isMedicationEprescribed: boolean = false; endDateHasPassed: boolean = false; isChronicMedication: boolean = false; showCancelRxCheckBox: boolean = null; showActionIcons : boolean = false; provider : ProviderModel = new ProviderModel() practiceErxRights : boolean = false; localProvider : ProviderModel = new ProviderModel() medicationAlreadyInInventory: boolean = false; treatmentPlan: TreatmentPlan = {} as TreatmentPlan; emrScriptID : string = ''; username: string; constructor( private medicationService : MedicationService, private dialog : MatDialog, private fb : UntypedFormBuilder, private prescriptionService : PrescriptionService, private treatmentPlanStateService: TreatmentPlanStateService ) { this.subscription = new Subscription() this.prescriptionService.practiceSettingsObserver.subscribe(practice => { if(!practice.be_Prescription){ this.practiceErxRights = false } else{ this.practiceErxRights = true } }) } async ngOnInit() : Promise<boolean> /*:void*/ { //PrescriptionType: "ePrescribed" try { this.isMedicationEprescribed = this.medication.PrescriptionType === 'ePrescribed' ? true : false if(this.medication.ProviderSpi !== ''){ let resultSpi:MedicationPermissionModel = this.spiPerList && this.spiPerList.length > 0 ? this.spiPerList.find((x) => x.ProviderSpi && x.ProviderSpi.indexOf(this.medication.ProviderSpi) > -1):undefined; if(!resultSpi) { let response: any = await this.medicationService.getProviderServiceLevelToPromise("", "", this.medication.ProviderSpi, "", 0); if (response !== null && response !== undefined /*&& response !== ""*/ && response.MessageType !== 'Error') { response = JSON.parse(response); if (response.MessageType == "Success" && response.MessageText !== null && response.MessageText !== '' && response.MessageText.PrescriberResponseItems.length > 0) { var providers = response.MessageText.PrescriberResponseItems[0].Prescriber; this.provider.FirstName = providers.PersonName.FirstName this.provider.LastName = providers.PersonName.LastName let providerAddress = new Address() providerAddress.Address1 = providers.AddressLine1 providerAddress.Address2 = providers.AddressLine2 providerAddress.City = providers.City providerAddress.State = providers.State this.provider.Address = providerAddress this.provider.Phone = providers.Number + providers.Extension if (providers !== null && providers !== '' && typeof (providers) !== 'undefined') { this.canProviderCancelRx = providers.bRxCancel; } } } const currentDate: Date = new Date(); let medicationEndDate: Date = new Date(this.medication.MedicationEndDate); if (this.medication.MedicationEndDate != null && typeof (this.medication.MedicationEndDate) != undefined && medicationEndDate <= currentDate) { this.endDateHasPassed = true; } if (!this.endDateHasPassed && this.canProviderCancelRx && this.medication.CanPharmacyCancel && this.isMedicationEprescribed) { if (this.medication.Ischronic && this.endDateHasPassed) { this.showCancelRxCheckBox = false; } else { // Open discontinue Summary screen this.showCancelRxCheckBox = true; } } else { // open discontinue window this.showCancelRxCheckBox = false; } let medPerObj: MedicationPermissionModel = { Id:this.medication.MedicationId, ProviderSpi:this.medication.ProviderSpi, medicationEndDate:medicationEndDate, canProviderCancelRx:this.canProviderCancelRx, canPharmacyCancel:this.medication.CanPharmacyCancel, endDateHasPassed:this.endDateHasPassed , isChronicMedication:this.medication.Ischronic, isMedicationEprescribed:this.isMedicationEprescribed, showCancelRxCheckBox:this.showCancelRxCheckBox }; this.prescriptionService.setSSProvMedPerList(medPerObj); } else if(resultSpi) { this.canProviderCancelRx = resultSpi.canProviderCancelRx; this.canPharmacyCancel = resultSpi.canPharmacyCancel; this.isChronicMedication = resultSpi.isChronicMedication; this.endDateHasPassed = resultSpi.endDateHasPassed; this.medication.Ischronic = resultSpi.isChronicMedication; this.showCancelRxCheckBox = resultSpi.showCancelRxCheckBox; } } else{ this.showCancelRxCheckBox = false; } this.checkMedicationOnHover(); this.loadStartupInfoFromStore(); return Promise.resolve(true); } catch (error) { return Promise.resolve(false); } } GetTodayDate() { var tdate = new Date(); var dd = tdate.getDate(); //yields day var MM = tdate.getMonth(); //yields month var yyyy = tdate.getFullYear(); //yields year var xxx = (MM + 1) + "/" + dd + "/" + yyyy; return xxx; } onDiscontinueReasonUpdated(event) { this.discontinueReason = event.reason; this.discontinueDescription = event.description; } }

and this is the html file for parent component

<div class=""> <div class="card card-default"> <div class="card-title"> <h4 class="d-flex align-items-center header-title"> <img src="assets/images/medications.svg" width="20" class="facesheet-svg mr-2" alt="" /> <span class="facesheet-title" [ngClass]="{ 'disabled-icon': (this.medicationList == null && this.pastMedicationList == null) || (this.medicationList == [] && this.pastMedicationList == []) }" (click)="onMedicationsListExpanded()"> <span>Medications&nbsp;</span> <span class="icon icon-expand fz-14"></span> </span> </h4> </div> <div class="card-body pt-0"> <div *ngIf="this.medicationList == null || this.medicationList?.length == 0" class="no-record-found"> <div class=""> <h5>No record found</h5> </div> </div> <ul *ngIf="this.medicationList != null && this.medicationList?.length != 0" class="header-listing medications-listing"> <li *ngFor="let medication of this.medicationList; let i = index"> <span mat-raised-button color="primary" [id]="index" #matMedicationButtonRef [mdePopoverTriggerFor]="appPopover" mdePopoverTriggerOn="hover" [mdePopoverEnterDelay]="500" (mouseleave)="matBtnOnLeave(popoverTrigger, index)" [mdePopoverTriggerFor]="appPopover" #popoverTrigger="mdePopoverTrigger" > {{ medication.MedicationName }} </span> <mde-popover #appPopover="mdePopover" [mdePopoverOverlapTrigger]="false" > <mat-card class="mde-popover-detailed" style="max-width: 400px"> <mat-card-content> <h4 class="popover-title">{{ medication.MedicationName }}</h4> <div class="popover-body px-0 pb-0"> <div class="row medication-details"> <div class="col-sm-4" style="align-self: baseline;"> <h5 class="mb-0">Direction</h5> </div> <div class="col-sm-8 pl-0"> <span>{{ getMedicationDirections(medication) }}</span> </div> </div> </div> </mat-card-content> </mat-card> </mde-popover> <app-medication-actions [ngClass]="this.showActionButtons ? '':'d-none'" [medication]="medication" [spiPerList]="this.spiPerList" (medicationPerMissionList)="this.onMedicationPerMissionList($event)" (discontinuedMedication)="this.onDiscontinueMedication($event)"></app-medication- actions> </li> </ul> </div> </div> </div>

The problem is with async ngOnInit() : Promise<boolean> in child component. There are four medication child components and I have added this duplication logic let resultSpi:MedicationPermissionModel = this.spiPerList && this.spiPerList.length > 0 ? this.spiPerList.find((x) => x.ProviderSpi && x.ProviderSpi.indexOf(this.medication.ProviderSpi) > -1):undefined;
if(!resultSpi) ` before calling to the getProviderServiceLevelToPromise function. I don't want to call it fours times if spiPerList already have a Providerspi code. But rather than checking the duplicate logic for each medicine or child component , system stayed at this line

this.prescriptionService.setSureScriptProviderMedPerList(medPerObj); `

and never goes up to the flow. this are the package.json

{ "name": "", "version": "0.0.0", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e", "build:elements": "ng build patientbanner --configuration production --output-hashing none && node concatenate.js" }, "private": true, "dependencies": { "@angular/animations": "^14.2.6", "@angular/cdk": "^14.2.5", "@angular/common": "^14.2.6", "@angular/compiler": "^14.2.6", "@angular/core": "^14.2.6", "@angular/elements": "^14.2.6", "@angular/forms": "^14.2.6", "@angular/material": "^14.2.5", "@angular/platform-browser": "^14.2.6", "@angular/platform-browser-dynamic": "^14.2.6", "@angular/router": "^14.2.6", "@angular/service-worker": "^14.2.6", "@dipaktelangre/age-calculator": "^1.0.7", "@fortawesome/fontawesome-free": "^6.0.0", "@fortawesome/fontawesome-svg-core": "^1.3.0", "@fortawesome/free-solid-svg-icons": "^6.0.0", "@kolkov/angular-editor": "^1.2.0", "@material-extended/mde": "^3.0.3", "@microsoft/signalr": "^6.0.9", "@ncstate/sat-popover": "^8.0.1", "@ngrx/component-store": "^12.5.1", "@ngrx/effects": "^12.5.1", "@ngrx/store": "^12.5.1", "@ngrx/store-devtools": "^12.5.1", "@popperjs/core": "^2.10.2", "@types/mixpanel": "^2.14.3", "@types/mixpanel-browser": "^2.35.7", "angular-file": "^3.6.0", "angular-formio": "^4.11.5", "angular-highcharts": "^12.0.0", "angular-split": "^14.0.0", "bootstrap": "^3.4.1", "browser-image-compression": "^2.0.0", "ckeditor4-angular": "^3.1.1", "concat": "^1.0.3", "dhtmlx-scheduler": "^5.3.8", "dragula": "^3.7.3", "fs-extra": "^10.1.0", "highcharts": "^9.2.2", "highcharts-angular": "^2.10.0", "lodash-es": "^4.17.21", "mixpanel-browser": "^2.41.0", "ng2-dragula": "^2.1.1", "ng2-tooltip-directive": "^2.10.3", "ngx-image-cropper": "^6.3.2", "ngx-infinite-scroll": "^10.0.1", "ngx-logger": "^4.2.2", "ngx-mat-select-search": "^4.0.2", "ngx-material-timepicker": "^5.5.3", "ngx-owl-carousel-o": "^6.0.0", "ngx-popperjs": "^12.2.1", "ngx-print": "^1.2.1", "ngx-toastr": "^14.3.0", "ngx-webcam": "^0.4.1", "recordrtc": "^5.6.2", "rxjs": "^6.6.7", "swiper": "^8.4.2", "tslib": "^2.2.0", "vanilla-text-mask": "^5.1.1", "wavesurfer.js": "^6.3.0", "zone.js": "~0.11.4" }, "devDependencies": { "@angular-devkit/build-angular": "^14.2.6", "@angular-eslint/builder": "12.1.0", "@angular-eslint/eslint-plugin": "12.1.0", "@angular-eslint/eslint-plugin-template": "12.1.0", "@angular-eslint/schematics": "^12.6.0", "@angular-eslint/template-parser": "12.1.0", "@angular/cli": "^14.2.6", "@angular/compiler-cli": "^14.2.6", "@types/dhtmlxscheduler": "^4.3.39", "@types/jasmine": "^3.6.11", "@types/jquery": "^3.5.10", "@types/node": "^12.20.55", "@typescript-eslint/eslint-plugin": "4.23.0", "@typescript-eslint/parser": "4.23.0", "angular-file": "^3.6.0", "eslint": "^7.26.0", "eslint-plugin-import": "2.22.1", "eslint-plugin-jsdoc": "30.7.6", "eslint-plugin-prefer-arrow": "1.2.2", "husky": "^6.0.0", "jasmine-core": "~3.6.0", "jasmine-spec-reporter": "~5.0.0", "karma": "~6.3.2", "karma-chrome-launcher": "~3.1.0", "karma-coverage": "~2.0.3", "karma-jasmine": "~4.0.0", "karma-jasmine-html-reporter": "^1.6.0", "ng-packagr": "^14.2.1", "prettier": "^2.3.1", "protractor": "~7.0.0", "ts-node": "~8.3.0", "tslint-config-prettier": "^1.18.0", "typescript": "~4.6.4" } }

Now control always stay at this.prescriptionService.setSureScriptProviderMedPerList(medPerObj);

Guide me. thank you!

Expected behaviour:

I want to stop calling this function this.medicationService.getProviderServiceLevelToPromise("", "", this.medication.ProviderSpi, "", 0); unless a unique this.medication.ProviderSpi exists.

0ma...@gmail.com

unread,
Feb 25, 2023, 3:02:17 PM2/25/23
to Angular and AngularJS discussion
Reply all
Reply to author
Forward
0 new messages