首页 > 解决方案 > 在不同组件中使用相同的对象数组,如果对一个对象进行任何更新,将在角度 8 中显示其他组件中的更新

问题描述

我在一个页面中使用了两个不同的组件,但在不同的部分。对象数组是从同一个服务调用中获取的。在一个组件中,我使用主机名和描述,但在第二个组件中,我显示了服务响应的所有值

我正在使用 contenteditable 对数据进行一些更改,并且在模糊时我正在更新对象数组中的更改。最后有一个保存按钮,它正在更新组件中数据库中的所有值。

第一个组件显示用户可以删除主机的主机列表。删除主机只会将其从对象数组中删除。因此,如果从第一个组件中删除主机,我希望将更改反映在第二个组件中。在我使用 rxjs 存储来维护状态之前,它不允许我对对象数组进行任何更改,并且给出的字段错误是只读的。

如果我对第一个组件数组进行任何更改,有什么办法会更新另一个组件数组。

这是我的代码:

import { Store } from '@ngrx/store';
import { ConfirmationDialogService } from '../../../../pages/setting/confirmation-dialog/confirmation-dialog.service';

import { NotifierService } from 'angular-notifier';
import { VulnerabilityScanService } from '../../../../services/vulnerability-scan.service';

@Component({
  selector: 'ngx-vuln-scan-scanned-host',
  templateUrl: './vuln-scan-scanned-host.component.html',
  styleUrls: ['./vuln-scan-scanned-host.component.scss'],
})
export class VulnScanScannedHostComponent implements OnInit {

  scannedHosts: any;
  distinctHosts: any;
  filter: any;
  isDelete: any;
  private notifier: NotifierService;
  constructor(private VulnerabilityScanService: VulnerabilityScanService,
     private confirmationDialogService: ConfirmationDialogService,
     notifier: NotifierService, 
     private store: Store<any>) 
     { this.notifier = notifier;}

  ngOnInit() {
    this.filter =  JSON.parse(localStorage.getItem('reportFilters'));

    this.VulnerabilityScanService.getReportDataOnHostSchedule(this.filter).subscribe(payload => {
      this.scannedHosts = payload;
        
      const key = 'ip'; 

      const arrayUniqueByKey = [...new Map(this.scannedHosts.map(item =>
      [item[key], item])).values()];

      this.isDelete = arrayUniqueByKey.length;
    });
  }
  
  removeHost(host, index){
    this.confirmationDialogService.confirm('Delete HOST', 'Do you want to delete selected HOST?')
    .then((confirmed) => {
      if (confirmed) {
        this.removeHostEntries(host, this.scannedHosts);
        console.log(this.scannedHosts);
        
        this.showNotification('success', 'HOST successfully deleted.');
        
      } else {

      }
    });
  }

  removeHostEntries(hostip, scannedHosts) {
    scannedHosts.forEach((value,index)=>{
        if(value.ip==hostip) scannedHosts.splice(index,1);
    });
  } 

  public showNotification(type: string, message: string): void {
    this.notifier.notify(type, message);
  }
} 

这是第二个组成部分:

import { Store } from '@ngrx/store';
import { VulnerabilityScanService } from '../../../../services/vulnerability-scan.service';

@Component({
  selector: 'ngx-vuln-scan-summary',
  templateUrl: './vuln-scan-summary.component.html',
  styleUrls: ['./vuln-scan-summary.component.scss'],
})
export class VulnScanSummaryComponent implements OnInit {

  @ViewChild('searchInput', { static: false }) searchInput: ElementRef;
  summaryList: any;
  editedList: any;
  showAlert: false;
  selectedOrderBy: any = '0';
  selectedFilterBy: any;
  public isDetailsOpen: boolean[] = [] ;
  
  // enableEditDesc : boolean[] = [];
  // enableEditDescIndex : boolean[] = [];
  
  

  constructor(private VulnerabilityScanService: VulnerabilityScanService,private store: Store<any>) {
  }

  ngOnInit() {

     this.selectedFilterBy =  JSON.parse(localStorage.getItem('reportFilters'));
     

       this.VulnerabilityScanService.getReportDataOnHostSchedule(this.selectedFilterBy).subscribe(payload => {
        this.summaryList = payload;
        console.log(this.summaryList)
      });
  }
 
  saveReport(data) {
    
    this.VulnerabilityScanService.saveReviewedReport(data).subscribe(payload => {
      console.log(payload);
    });
  }

  toggleRow(i: any) {
    this.isDetailsOpen[i] = !this.isDetailsOpen[i];
  }

  

}

标签: angulartypescriptcomponentsobservable

解决方案


如果您不想使用状态管理,我会尝试这样的事情。

定义一个共享单例服务。

@Injectable({ providedIn: 'root' })
export class ReportDataStore {
  private _data: any[];
  
  get data() {
    return this._data;
  }

  set data(d) {
    return this._data = d;
  }

}

将其注入两个组件并设置数据。

  this.VulnerabilityScanService.getReportDataOnHostSchedule(this.filter).subscribe(payload => {
      this.reportDataStore.data = payload;
      this.scannedHosts = this.reportDataStore.data;
        
      const key = 'ip'; 

      const arrayUniqueByKey = [...new Map(this.scannedHosts.map(item =>
      [item[key], item])).values()];

      this.isDelete = arrayUniqueByKey.length;
    });


   this.VulnerabilityScanService.getReportDataOnHostSchedule(this.selectedFilterBy).subscribe(payload => {
        this.reportDataStore.data = payload;
        this.summaryList = this.reportDataStore.data;
        console.log(this.summaryList)
      });


组件中的局部变量现在应该维护对 ReportDataStore 服务中相同数组的引用。


推荐阅读