У меня Angular Приложение, у меня есть всплывающее окно предварительного просмотра в моем компоненте данных списка, всплывающее окно предварительного просмотра является компонентом диалога.
теперь, когда я нажимаю кнопку из моего списка, я передаю идентификатор элемента списка, в диалоговых окнах отображаются данные из компонента диалога на основе переданного ему идентификатора. теперь я установил некоторые действия в диалоговом окне, например Отметить как завершенное, он вызывает функцию в компоненте диалогового окна и обновляет базу данных, теперь я хочу, чтобы после обновления базы данных я обновил sh свой компонент списка последними данными.
вот мой код:
компонент диалога или (TaskspopupviewpcComponent):
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { Component, OnInit, Inject,SecurityContext} from '@angular/core';
import {TaskscalendarviewpcComponent} from '../taskscalendarviewpc/taskscalendarviewpc.component';
import { DialogService } from '../../../../shared/services/dialog.service';
import { MatDialog } from '@angular/material/dialog';
import { ITasks } from '../../../models/tasks.model';
import { TasksService } from '../../../services/tasks.service';
import { DomSanitizer } from '@angular/platform-browser'
import { formatDate } from '@angular/common';
//--------we add the router here for edit to redirect to edit form-----//
import { ActivatedRoute,Router } from '@angular/router';
export class TasksData {
constructor(public dynamicdata: string, public id: number, public action: string, public text: string, public type: string) {}
}
@Component({
selector: 'app-taskspopupviewpc',
templateUrl: './taskspopupviewpc.component.html',
styleUrls: ['./taskspopupviewpc.component.scss'],
//template:`<app-taskscalendarviewpc #component1></app-taskscalendarviewpc>`
})
export class TaskspopupviewpcComponent implements OnInit {
action;
close;
taskId: number;
taskResult;
type: string;
taskname;
category;
startdate;
enddate;
textContent;
textContent1;
editorReadSantStyle = {
height: '100px',
alignment:'MJ Selected-Quill'
};
constructor(
private _router:Router,
private _activatedRoute: ActivatedRoute,
public dialog: MatDialog,
private dialogService: DialogService,
private taskservice:TasksService,
public callRef: MatDialogRef<TaskspopupviewpcComponent>,
@Inject(MAT_DIALOG_DATA) public data: TasksData,
private sanitizer?: DomSanitizer,
) {
this.taskId = data.id;
this.action = data.action;
this.close = data.text;
this.type = data.type;
}
ngOnInit(): void {
this.getTaskById(this.taskId);
}
closeWindow(): void {
this.callRef.close(false);
}
getTaskById(id) {
this.taskservice.getTaskById(id,'/tasks/').subscribe(
(thetask: ITasks) => this.dispalyTask(thetask),
error => {
const res = this.dialogService.ErrorDialog('Server Error', 'Sorry, the system is unavailable at the moment.', 'Close', 'Try Again');
res.afterClosed().subscribe(dialogResult => {
if (dialogResult) {
//this.callNext(200);
}
});
}
);
}
dispalyTask(task: ITasks) {
this.taskResult = task[0];
console.log(this.taskResult);
this.taskId = task[0].TaskID;
this.taskname = task[0].TaskName;
this.category = task[0].CategoryName;
this.startdate = formatDate(task[0].StartDate,'yyyy-MM-dd','en_US');
this.enddate = formatDate(task[0].EndDate,'yyyy-MM-dd','en_US');
//---fore here we hide the description----//
//this.textContent = this.HTMLSant(task[0].Description);
}
HTMLSant(html:string){
return this.sanitizer.bypassSecurityTrustHtml(html);
}
markAsComplete(taskId){
console.log(taskId);
this.closeWindow();
if(taskId>0){
console.log('-----Update task-----');
const result = {"TaskID":taskId,"Status":true};
this.taskservice.updateStatus(result, taskId, '/tasks/updatestatus/').subscribe(
res => {
if (res) {
this.dialogService.MessageBox('Marked as Complete', 'X', 100, 'SuccessMessage');
//this.callNext(1000);
//this.refreshCalendar(100);
} else {
this.dialogService.MessageBox('Error updating record', 'X', 5000, 'ErrorMessage');
}
},
error => {
const res = this.dialogService.ErrorDialog(
'Server Error',
'Sorry, the system is unavailable at the moment.',
'Close',
'Try Again'
);
res.afterClosed().subscribe(dialogResult => {
if (dialogResult) {
//this.callNext(200);
}
});
}
);
}
}
editTask(taskId:number){
console.log(taskId);
this.closeWindow();
this._router.navigate(['./tasks/alltasks/addtask/',taskId]);
}
}
компонент моего списка или (TaskscalendarviewpcComponent):
import {Component,ChangeDetectionStrategy,ViewChild,TemplateRef, OnInit} from '@angular/core';
import {startOfDay, endOfDay, subDays, addDays, endOfMonth, isSameDay, isSameMonth, addHours,} from 'date-fns';
import { Subject } from 'rxjs';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { CalendarEvent, CalendarEventAction, CalendarEventTimesChangedEvent, CalendarView,} from 'angular-calendar';
import { ITasks } from '../../../models/tasks.model';
import { TasksService } from '../../../services/tasks.service';
import { DialogService } from '../../../../shared/services/dialog.service';
import { MatDialog } from '@angular/material/dialog';
//import { CalendarEventActionsComponent } from 'angular-calendar/modules/common/calendar-event-actions.component';
import { TasksData, TaskspopupviewpcComponent } from '../taskspopupviewpc/taskspopupviewpc.component';
const colors: any = {
red: {
primary: '#ad2121',
secondary: '#FAE3E3',
},
blue: {
primary: '#1e90ff',
secondary: '#D1E8FF',
},
yellow: {
primary: '#e3bc08',
secondary: '#FDF1BA',
},
};
@Component({
selector: 'app-taskscalendarviewpc',
templateUrl: './taskscalendarviewpc.component.html',
styleUrls: ['./taskscalendarviewpc.component.scss'],
providers: [DialogService]
})
export class TaskscalendarviewpcComponent implements OnInit {
@ViewChild('modalContent', { static: true }) modalContent: TemplateRef<any>;
view: CalendarView = CalendarView.Month;
CalendarView = CalendarView;
viewDate: Date = new Date();
modalData: {
action: string;
event: CalendarEvent;
};
actions: CalendarEventAction[] = [
{
label: '<i class="fas fa-fw fa-pencil-alt"></i>',
a11yLabel: 'Edit',
onClick: ({ event }: { event: CalendarEvent }): void => {
this.handleEvent('Edited', event);
},
},
{
label: '<i class="fas fa-fw fa-trash-alt"></i>',
a11yLabel: 'Delete',
onClick: ({ event }: { event: CalendarEvent }): void => {
this.events = this.events.filter((iEvent) => iEvent !== event);
this.handleEvent('Deleted', event);
},
},
];
refresh: Subject<any> = new Subject();
events: CalendarEvent[] = [];
activeDayIsOpen: boolean = true;
constructor(
private modal: NgbModal,
public dialog: MatDialog,
private dialogService: DialogService,
private taskservice:TasksService) {}
ngOnInit(){
console.log('---------Hi call db-----');
this.getAllmyTasks();
}
getAllmyTasks(){
this.taskservice.getAllMyPendingTasks('/tasks/getallmypendingtasks').subscribe(
(myDbData: ITasks[]) => {
console.log(myDbData);
myDbData.forEach((item)=>{
this.events.push({
id:item.TaskID,
start:new Date(item.StartDate),
end:new Date(item.EndDate),
title:item.TaskName,
color: colors.yellow,
actions: this.actions
})
});
this.viewDate = new Date();
},
error => {
const res = this.dialogService.ErrorDialog('Server Error', 'Sorry, the system is unavailable at the moment.', 'Close', 'Try again');
res.afterClosed().subscribe(dialogResult => {
if (dialogResult) {
//this.callNext(200);
}
});
}
);
}
openPreview(action: string, event: CalendarEvent): void {
let id:number = Number(event.id);
const res = new TasksData('{data}', id, 'open', 'X', 'view');
const req = this.dialog.open(TaskspopupviewpcComponent, { data: res, panelClass: 'mj-preview-modal' });
req.afterClosed().subscribe(dataBox => {
if (dataBox) {
const data = dataBox;
}
});
}
//---------Calendar------------------------//
dayClicked({ date, events }: { date: Date; events: CalendarEvent[] }): void {
//--note this.viewDate is current date;
console.log(date);
if (isSameMonth(date, this.viewDate)) {
if (
(isSameDay(this.viewDate, date) && this.activeDayIsOpen === true) ||
events.length === 0
) {
this.activeDayIsOpen = false;
} else {
this.activeDayIsOpen = true;
}
this.viewDate = date;
}
}
eventTimesChanged({
event,
newStart,
newEnd,
}: CalendarEventTimesChangedEvent): void {
this.events = this.events.map((iEvent) => {
if (iEvent === event) {
return {
...event,
start: newStart,
end: newEnd,
};
}
return iEvent;
});
this.handleEvent('Dropped or resized', event);
}
handleEvent(action: string, event: CalendarEvent): void {
console.log(action);
console.log('--------xxx------');
console.log(event.id);
let TaskId = event.id;
this.modalData = { event, action };
this.modal.open(this.modalContent, { size: 'lg' });
}
addEvent(): void {
this.events = [
...this.events,
{
title: 'New event',
start: startOfDay(new Date()),
end: endOfDay(new Date()),
color: colors.red,
draggable: true,
resizable: {
beforeStart: true,
afterEnd: true,
},
},
];
}
deleteEvent(eventToDelete: CalendarEvent) {
this.events = this.events.filter((event) => event !== eventToDelete);
}
setView(view: CalendarView) {
this.view = view;
}
closeOpenMonthViewDay() {
this.activeDayIsOpen = false;
}
}
введите описание изображения здесь