как обновить один компонент из другого компонента после обновления - PullRequest
0 голосов
/ 24 сентября 2019

У меня есть два компонента, и я хочу обновить компонент 1 после действия компонента 2

это моя app-pru-card:

import { Component, OnInit, Input } from '@angular/core';
import { Pru } from 'app/models/pru.model';
import * as moment from "moment";
import { MatDialog } from '@angular/material';
import { UpdatePruComponent } from './update-pru/upadate-pru.component';
import { FwaasService } from 'app/services/fwaas.service';
import { NgxSpinnerService } from 'ngx-spinner';
import { ToastrService } from 'ngx-toastr';
@Component({
  selector: 'app-pru-card',
  templateUrl: './pru-card.component.html',
  styleUrls: ['./pru-card.component.scss']
})
export class PruCardComponent implements OnInit {
  @Input() pru: Pru;
  @Input() clients_name: any;

  constructor(private dialog: MatDialog, private _fwaasService: FwaasService, private spinner: NgxSpinnerService, private toastr: ToastrService) { }
  ngOnInit() {
  }
  public getStatus(pru: Pru) {
    var todayDate = new Date(new Date().toUTCString());
    var utcStartDateString = new Date(pru.start);
    var utcEndDateString = new Date(pru.end);
    if (pru.last_change && pru.last_change.change_fails.length > 0) {
      return 'Failed';
    }
    else {
      if (utcEndDateString < todayDate) return 'Deactivated';
      if (utcStartDateString > todayDate && utcEndDateString > todayDate) return 'Planned';
      if (utcStartDateString <= todayDate && utcEndDateString >= todayDate) return 'Activated';
    }
  }
  getDatePru(date: string) {
    var utcDateString = new Date(date);
    utcDateString = moment.utc(utcDateString).toDate();
    // return moment.utc(utcDateString).local().format('YYYY-MM-DD'); // pour afficher la date local de navigateur
    return moment.utc(utcDateString).toDate().toLocaleDateString("fr-FR", { timeZone: "Europe/Paris" });
  }
  getTimePru(date: string) {
    var utcDateString = new Date(date);
    // return moment.utc(utcDateString).local().format(' HH:mm:ss'); // pour afficher l'heure local de navigateur
    return moment.utc(utcDateString).toDate().toLocaleTimeString("fr-FR", { timeZone: "Europe/Paris" });
  }
  getComment(pru: Pru) {
    if (pru.last_change) {
      var utcDateString = new Date(pru.last_change.update_time);
      utcDateString = moment.utc(utcDateString).toDate();
      // return moment.utc(utcDateString).local().format('YYYY-MM-DD'); // pour afficher la date local de navigateur
      var dateLastComment = moment.utc(utcDateString).toDate().toLocaleDateString("fr-FR", { timeZone: "Europe/Paris" });
      var timeastComment = moment.utc(utcDateString).toDate().toLocaleTimeString("fr-FR", { timeZone: "Europe/Paris" });
      return "\n" + dateLastComment + " - " + timeastComment + ":  " + pru.last_change.comment;
    }
    else return "";
  }

  getCommentFailed(pru: Pru) {
    if (pru.last_change && pru.last_change.change_fails.length == 1) {
      return "\n" + "name :  " + pru.last_change.change_fails[0].name + "\n" + "type   :  " + pru.last_change.change_fails[0].type;
    }
    else if(pru.last_change && pru.last_change.change_fails.length == 2){
      return "\n" + "name :  " + pru.last_change.change_fails[0].name + "\n" + "type   :  " + pru.last_change.change_fails[0].type + "\n" + "name :  " + pru.last_change.change_fails[1].name + "\n" + "type   :  " + pru.last_change.change_fails[1].type;

    }
    else if(pru.last_change && pru.last_change.change_fails.length == 3){
      return "\n" + "name :  " + pru.last_change.change_fails[0].name + "\n" + "type   :  " + pru.last_change.change_fails[0].type + "\n" + "name :  " + pru.last_change.change_fails[1].name + "\n" + "type   :  " + pru.last_change.change_fails[1].type + "\n" + "name :  " + pru.last_change.change_fails[2].name + "\n" + "type   :  " + pru.last_change.change_fails[2].type;

    }
    else if(pru.last_change && pru.last_change.change_fails.length == 4){
      return "\n" + "name :  " + pru.last_change.change_fails[0].name + "\n" + "type   :  " + pru.last_change.change_fails[0].type + "\n" + "name :  " + pru.last_change.change_fails[1].name + "\n" + "type   :  " + pru.last_change.change_fails[1].type + "\n" + "name :  " + pru.last_change.change_fails[2].name + "\n" + "type   :  " + pru.last_change.change_fails[2].type + "\n" + "name :  " + pru.last_change.change_fails[3].name + "\n" + "type   :  " + pru.last_change.change_fails[3].type;

    }
    else return "";
  }

  onUpdatePru(selectedPru) {

    const dialogRef = this.dialog.open(UpdatePruComponent, { minWidth: '600px', maxWidth: '800px' });
    dialogRef.componentInstance.pru = { ...selectedPru };
    dialogRef.componentInstance.client_name = this.clients_name;

  }

  refreshPru(pru: Pru) {
    this.spinner.show();
    this._fwaasService.getRefreshPru(pru.name, this.clients_name).subscribe(res => {
      this.pru = res;
      this.spinner.hide();
      this.toastr.success(pru.name, 'is  successfully refresh');
    });
    error => {
      setTimeout(() => {
        this.spinner.hide();
      }, 1000);
    }
  }

}

mu component.html:

<div class="page-layout blank " fusePerfectScrollbar>
  <div class="header accent p-24 h-120" fxLayout="row" fxLayoutAlign="start center">
    <div fxLayout="column" fxLayoutAlign="center start">
      <div fxLayout="row" fxLayoutAlign="start center">
        <mat-icon class="secondary-text s-18">home</mat-icon>
        <mat-icon class="secondary-text s-16">chevron_right</mat-icon>
        <span class="secondary-text">Firewall</span>
        <mat-icon class="secondary-text s-16">chevron_right</mat-icon>
        <span class="secondary-text">PRU</span>
      </div>
      <div class="h1 mt-16">PRU</div>
    </div>
  </div>
  <div class="p-24">
    <div fxLayout="row" fxLayoutAlign="start center" class="mat-card mat-elevation-z4 p-16" style="border-radius : 5px">
      <ng-select [items]="clients" bindLabel="name" bindValue="id" placeholder="{{'PRU.Select client' | translate}}"
        (change)="onClientsClick($event)" [clearable]='false' fxFlex="30%">
      </ng-select>
    </div>
    <mat-progress-bar *ngIf="isLoadingPru" mode="indeterminate"></mat-progress-bar>
    <div class="mat-card mat-elevation-z4 p-16 mt-16" style="border-radius : 3px" *ngIf="Pru">
      <div class="mb-16" fxLayout="row" fxLayoutAlign="space-between center">
        <mat-form-field appearance="outline" fxFlex="33" *ngIf="Pru">
          <mat-label>{{ 'PRU.SEARCH' | translate }}</mat-label>
          <input matInput type="text" (keyup)="searchPru($event.target.value)" [(ngModel)]="searchValue">
        </mat-form-field>
        &nbsp; &nbsp;
        <mat-form-field appearance="outline" fxFlex="47" *ngIf="Pru" style="margin-right: 6%">
          <input matInput type="text" placeholder="" style="display: none">
          <mat-label> {{'PRU.ADVANCED SEARCH' | translate}} : </mat-label>
          <mat-radio-group aria-labelledby="example-radio-group-label" class="example-radio-group">
            <mat-radio-button class="example-radio-button all" value="all" (click)="searchAll()"
              [checked]=" resetSearch == true">
              {{'PRU.ALL' | translate}} </mat-radio-button>
            <mat-radio-button class="example-radio-button activated " value="activated" (click)="searchActivated()">
              {{'PRU.Activated' | translate}} </mat-radio-button>
            <mat-radio-button class="example-radio-button deactivated" value="deactivated"
              (click)="searchDeactivated()">
              {{'PRU.Deactivated' | translate}} </mat-radio-button>
            <mat-radio-button class="example-radio-button planned" value="planned" (click)="searchPlanned()">
              {{'PRU.Planned' | translate}} </mat-radio-button>
            <mat-radio-button class="example-radio-button failed" value="failes" (click)="searchFailed()">
              {{'PRU.Failed' | translate}} </mat-radio-button>
          </mat-radio-group>
        </mat-form-field>

        <button class="butnRefresh" style="margin-right: 50px;" (click)="getAllPruList()"><i class="fa fa-refresh"></i>
          {{'PRU.Refresh All' | translate}} </button>

      </div>


      <div class="mat-card mat-elevation-z4 p-16 mt-16" style="border-radius : 3px" *ngIf="!Pru">
        <p> {{ 'PRU.No data to display' | translate }}</p>
      </div>
      <mat-grid-list cols="3" rowHeight="320px">
        <mat-grid-tile *ngFor="let pru of Pru">
          <app-pru-card [pru]="pru" [clients_name]="clients_name" class="app-pru-card"></app-pru-card>
        </mat-grid-tile>
      </mat-grid-list>
    </div>
  </div>

component1.ts:

 import { Component, OnInit, Output, Input } from '@angular/core';
import { FuseTranslationLoaderService } from '@fuse/services/translation-loader.service';
import { locale as english } from 'app/pages/fwaas/pru/i18n/en';
import { locale as french } from 'app/pages/fwaas/pru/i18n/fr';
import { FwaasService } from 'app/services/fwaas.service';
import { Client } from 'app/models/client.model';
import { Pru } from 'app/models/pru.model';
import { ToastrService } from 'ngx-toastr';
import { EventEmitter } from 'events';

@Component({
  selector: 'app-pru',
  templateUrl: './pru.component.html',
  styleUrls: ['./pru.component.scss']
})
export class PRUComponent implements OnInit {
  clients: any;
  PruInitialList: any;
  isLoadingPru: boolean;
  resetSearch: boolean;
  searchValue: any;
  clients_name: string;
  @Output()  emitEvent = new EventEmitter();
  @Input() Pru : any
  constructor(private _fuseTranslationLoaderService: FuseTranslationLoaderService, private fwaasservice: FwaasService, private toastr: ToastrService) {
    this._fuseTranslationLoaderService.loadTranslations(english, french);
    }

  ngOnInit() {
    this.resetSearch = true;
    this.fwaasservice.getClients().subscribe(res => {
      this.clients = res;
    });  }

  getAllPruList(clients_name) {
    this.fwaasservice.getPruList(this.clients_name).subscribe(res => {
      this.Pru = res;
      this.isLoadingPru = false;
      this.PruInitialList = res;
      this.toastr.success('Pru is  successfully updated');
    });
  }


  onClientsClick(clients: Client) {
    this.searchValue = "";
    this.clients_name = clients.name;
    this.isLoadingPru = true;
    this.Pru = null;
    this.fwaasservice.getPruList(clients.name).subscribe(res => {
      this.Pru = res;
      this.isLoadingPru = false;
      this.PruInitialList = res;
    },
      error => {
        setTimeout(() => {
          this.isLoadingPru = false;
        }, 1000);
      });
  }

  public searchPru = (value: string) => {
    this.resetSearch = true;
    let virtualServersFilteredList: any;
    if (this.PruInitialList) {
      virtualServersFilteredList = this.PruInitialList
        .filter(pru => pru.name.toLowerCase().indexOf(value.trim().toLocaleLowerCase()) !== -1);
      this.Pru = virtualServersFilteredList;
    }
  }
  public searchActivated = () => {
    this.resetSearch = false;
    this.searchValue = "";
    let virtualServersFilteredList: any;
    if (this.PruInitialList) {
      virtualServersFilteredList = this.PruInitialList
        .filter(pru => this.getStatus(pru) == 'Activated');
      this.Pru = virtualServersFilteredList;
    }
  }

  public searchDeactivated = () => {
    this.resetSearch = false;
    this.searchValue = "";
    let virtualServersFilteredList: any;
    if (this.PruInitialList) {
      virtualServersFilteredList = this.PruInitialList
        .filter(pru => this.getStatus(pru) == 'Deactivated');
      this.Pru = virtualServersFilteredList;
    }
  }
  public searchPlanned = () => {
    this.resetSearch = false;
    this.searchValue = "";
    let virtualServersFilteredList: any;
    if (this.PruInitialList) {
      virtualServersFilteredList = this.PruInitialList
        .filter(pru => this.getStatus(pru) == 'Planned');
      this.Pru = virtualServersFilteredList;
    }
  }
  public searchAll = () => {
    this.resetSearch = true;
    this.searchValue = "";
    if (this.PruInitialList) {
      this.Pru = this.PruInitialList;
    }
  }
  searchFailed = () => {
    this.resetSearch = false;
    this.searchValue = "";
    let virtualServersFilteredList: any;
    if (this.PruInitialList) {
      virtualServersFilteredList = this.PruInitialList
        .filter(pru => this.getStatus(pru) == 'Failed');
      this.Pru = virtualServersFilteredList;
    }
  }

  public getStatus(pru: Pru) {
    var todayDate = new Date(new Date().toUTCString());
    var utcStartDateString = new Date(pru.start);
    var utcEndDateString = new Date(pru.end);
    if (pru.last_change && pru.last_change.change_fails.length > 0) {
      return 'Failed';
    }
    else {
      if (utcEndDateString < todayDate) return 'Deactivated';
      if (utcStartDateString > todayDate && utcEndDateString > todayDate) return 'Planned';
      if (utcStartDateString <= todayDate && utcEndDateString >= todayDate) return 'Activated';
    }
  }

}

это компонент 2, когда я делаю свое обновление действия после обновления, я хочу обновить компонент 1, как это сделать, пожалуйста:

import { Component, OnInit, Inject, Input, ViewChild, Output, EventEmitter } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA, MatDialog } from '@angular/material';
import { FuseTranslationLoaderService } from '@fuse/services/translation-loader.service';
import { locale as english } from 'app/pages/lbaas/vs-card/i18n/en';
import { locale as french } from 'app/pages/lbaas/vs-card/i18n/fr';
import { NgxSpinnerService } from 'ngx-spinner';
import { Pru } from 'app/models/pru.model';
import * as moment from "moment";
import { UpdateConfirmationComponent } from './update-confirmation/update-confirmation.component';
import { FwaasService } from 'app/services/fwaas.service';
import { ToastrService } from 'ngx-toastr';
import { DateTimeAdapter } from 'ng-pick-datetime';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { PruCardComponent } from '../pru-card.component';
import { PRUComponent } from '../../pru/pru.component';

@Component({
  selector: 'app-upadate-pru',
  templateUrl: './upadate-pru.component.html',
  styleUrls: ['./upadate-pru.component.scss']
})

export class UpdatePruComponent implements OnInit {
  public selectedMoment = new Date();
  updateForm: FormGroup;
  @Input() pru: any;
  buttonClicked: string;
  public dateNow: any;
  public minDateEnd: any;
  dateStart: any;
  dateEnd: any;
  change_fails = [];
  @Output() 
  emitEvent = new EventEmitter();
    constructor(@Inject(MAT_DIALOG_DATA) public PruComponent: PRUComponent, private _fuseTranslationLoaderService: FuseTranslationLoaderService, private _formBuilder: FormBuilder, public showDialogRef: MatDialogRef<UpdatePruComponent>, private spinner: NgxSpinnerService, private dialog: MatDialog, private _fwaasService: FwaasService, @Inject(MAT_DIALOG_DATA) public client_name, private toastr: ToastrService, private dateTimeAdapter: DateTimeAdapter<any>) {
    this._fuseTranslationLoaderService.loadTranslations(english, french);
    this.dateTimeAdapter.setLocale('fr-FR'); // change locale to fr
  }

  ngOnInit() {
    this.updateForm = this._formBuilder.group({
      dateStart: [this.pru.start],
      dateEnd: [this.pru.end, Validators.required],
      comment: ['', Validators.required]
    });
    this.dateStart = this.pru.start;
    this.dateEnd = this.pru.end;
    var date = new Date();
    date.toLocaleDateString("fr-FR", { timeZone: "Europe/Paris" });
    this.dateNow = date.toISOString();
    this.minDateEnd = this.updateForm.value.dateStart;
    this.setCommentFailed();

  }

  public getStatus(pru: Pru) {
    var todayDate = new Date(new Date().toUTCString());
    var utcStartDateString = new Date(pru.start);
    var utcEndDateString = new Date(pru.end);
    if (pru.last_change && pru.last_change.change_fails.length > 0) {
      return 'Failed';
    }
    else {
      if (utcEndDateString < todayDate) return 'Deactivated';
      if (utcStartDateString > todayDate && utcEndDateString > todayDate) return 'Planned';
      if (utcStartDateString <= todayDate && utcEndDateString >= todayDate) return 'Activated';
    }
  }
  getDatePru(date: string) {
    var utcDateString = new Date(date);
    utcDateString = moment.utc(utcDateString).toDate();
    // return moment.utc(utcDateString).local().format('YYYY-MM-DD'); // pour afficher la date local de navigateur
    return moment.utc(utcDateString).toDate().toLocaleDateString("fr-FR", { timeZone: "Europe/Paris" });
  }
  getTimePru(date: string) {
    var utcDateString = new Date(date);
    // return moment.utc(utcDateString).local().format(' HH:mm:ss'); // pour afficher l'heure local de navigateur
    return moment.utc(utcDateString).toDate().toLocaleTimeString("fr-FR", { timeZone: "Europe/Paris" });
  }
  getComment(pru: Pru) {
    if (pru.last_change) {
      var utcDateString = new Date(pru.last_change.update_time);
      utcDateString = moment.utc(utcDateString).toDate();
      // return moment.utc(utcDateString).local().format('YYYY-MM-DD'); // pour afficher la date local de navigateur
      var dateLastComment = moment.utc(utcDateString).toDate().toLocaleDateString("fr-FR", { timeZone: "Europe/Paris" });
      var timeastComment = moment.utc(utcDateString).toDate().toLocaleTimeString("fr-FR", { timeZone: "Europe/Paris" });
      return "\n" + dateLastComment + " - " + timeastComment + ":  " + pru.last_change.comment;
    }
    else return "";
  }

  getCommentFailed(pru: Pru) {
    if (pru.last_change && pru.last_change.change_fails.length == 1) {
      return "\n" + "name :  " + pru.last_change.change_fails[0].name + "\n" + "type   :  " + pru.last_change.change_fails[0].type;
    }
    else if(pru.last_change && pru.last_change.change_fails.length == 2){
      return "\n" + "name :  " + pru.last_change.change_fails[0].name + "\n" + "type   :  " + pru.last_change.change_fails[0].type + "\n" + "name :  " + pru.last_change.change_fails[1].name + "\n" + "type   :  " + pru.last_change.change_fails[1].type;

    }
    else if(pru.last_change && pru.last_change.change_fails.length == 3){
      return "\n" + "name :  " + pru.last_change.change_fails[0].name + "\n" + "type   :  " + pru.last_change.change_fails[0].type + "\n" + "name :  " + pru.last_change.change_fails[1].name + "\n" + "type   :  " + pru.last_change.change_fails[1].type + "\n" + "name :  " + pru.last_change.change_fails[2].name + "\n" + "type   :  " + pru.last_change.change_fails[2].type;

    }
    else if(pru.last_change && pru.last_change.change_fails.length == 4){
      return "\n" + "name :  " + pru.last_change.change_fails[0].name + "\n" + "type   :  " + pru.last_change.change_fails[0].type + "\n" + "name :  " + pru.last_change.change_fails[1].name + "\n" + "type   :  " + pru.last_change.change_fails[1].type + "\n" + "name :  " + pru.last_change.change_fails[2].name + "\n" + "type   :  " + pru.last_change.change_fails[2].type + "\n" + "name :  " + pru.last_change.change_fails[3].name + "\n" + "type   :  " + pru.last_change.change_fails[3].type;

    }
    else return "";
  }
  setDateNow(pru) {
    var date = new Date();
    date.toLocaleDateString("fr-FR", { timeZone: "Europe/Paris" });
    pru.start = date.toISOString();
    pru.end = date.toISOString();
  }

  setCommentFailed() {

    if (this.getStatus(this.pru) == 'Failed') {
      this.updateForm.get('comment').setValue(this.pru.last_change.comment);
    }
    this.updateForm.get('comment').updateValueAndValidity()
  }
  setminDateEnd(dateValue: string): void {
    this.minDateEnd = this.updateForm.value.dateStart;
  }
  onUpdatePru(pru) {
    if (this.buttonClicked == 'dateEndNow') {
      var date = new Date();
      date.toLocaleDateString("fr-FR", { timeZone: "Europe/Paris" });
      this.dateEnd = date.toISOString();
    }
    if (this.buttonClicked == 'dateStartNow') {
      var date = new Date();
      date.toLocaleDateString("fr-FR", { timeZone: "Europe/Paris" });
      this.dateStart = date.toISOString();
    }
    else if ((this.buttonClicked == 'update') && (this.updateForm.valid)) {

      const dialogRef = this.dialog.open(UpdateConfirmationComponent, {
        minWidth: '400px', maxWidth: '800px',
        data: { name: pru.name, start: this.updateForm.value.dateStart, end: this.updateForm.value.dateEnd }
      });
      dialogRef.componentInstance.pru = { ...pru };
      dialogRef.afterClosed().subscribe(result => {
        if (result != null) {
          this.spinner.show();
          //  updatePru(pruName , start , end , comment , clientName) {
          this._fwaasService.updatePru(pru.name, this.updateForm.value.dateStart, this.updateForm.value.dateEnd, this.updateForm.value.comment, this.client_name).subscribe(res => {
            //shoold update pru after activate or deactivate
            this._fwaasService.getDetails(pru.name, this.client_name).subscribe(res => {
              this.pru = res;
              this.pru.last_change.comment = res.last_change.comment;
            });
            this.emitEvent.next(this.pru)
            this.spinner.hide();
            this.toastr.success(pru.name, 'is  successfully updated');
          },
            error => {
              setTimeout(() => {
                this.spinner.hide();
              }, 1000);
            }

          );

        }
      }
      );
    }
  }
  onCancelClick(): void {
    this.showDialogRef.close();
  }
}

на функции onUpdatePru Я хочу обновить компонент 1, как это сделать, пожалуйста, спасибо за ваше время

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...