首页 > 解决方案 > 有角度的孩子对孩子的交流

问题描述

我有一个父组件,它呈现第一个子组件,即 app-deals-transaction ,主组件是 transactions-details.component,然后 app-deals-transaction 呈现 2 个子组件,即 app-deals-approval 组件和 app-表多排序组件。

如何创建一个服务来从 deal-approval.component.ts 通信 deal-transaction.component.ts ?

我想要的是,如果有变化,或者如果在 deal-transaction.component.ts 中调用了 _pageEventDealsList,我还想同时调用并执行 deal-approval.component.ts 中的 _pageEventDealsForApprovalList

我们如何在 angular 中做到这一点?每次在 deal-transaction.component.ts 组件中调用或执行 _pageEventDealsList 时,都会执行 deal-approval.component.ts 中的 _pageEventDealsForApprovalList。谢谢。

#app-deals-transaction 组件 html 代码

<div >
   <app-deals-approval  [transaction]="transaction" ></app-deals-approval> 
  </div>
  <app-table-multi-sort (dataServiceEvent)="dealsServiceEvent($event)" [tableOptions]="tableOptions" [tableData]="data" (tableActionsEvent)="tableActions($event)"></app-table-multi-sort>
</div>

#app-deals-approval 组件 html 代码 <app-table-multi-sort (dataServiceEvent)="dataForApprovalServiceEvent($event)" [tableOptions]="tableOptions" [tableData]="data">

#app-deals-approval 组件 ts 代码

export class DealsApprovalComponent implements OnInit {
  @ViewChild(TableMultiSortComponent, { static: true }) tableMultiSortComponent: TableMultiSortComponent;
  tableOptions: any;
  @Input() transaction: any;
  @Input() dataTest: any;
  isLoading: boolean;
  private _destroyed$ = new Subject();
  totalDeals : number;
  accountId: any;
  data: any;
  searchInput: string;
  table: any;
  constructor(
    private dialog: MatDialog,
    private dealService: DealService,
    private notificationService: NotificationService,
    private route: Router,
    
  ) {}
  ngOnInit(): void {
    console.log("load here" , this.dataTest)
  
    const currentAccountDetails = localStorage.getItem('currAcct') as any;
    if (currentAccountDetails) {
      this.accountId = JSON.parse(currentAccountDetails).accountId;
    }

    this.tableOptions = {
      columns:[
        {id:'name',name:'Deal Name',subId:'type', subtitle:'Deal Type'},
        {id:'annualRentProposed',name:'Annual Rent (Proposed)', subId: 'annualRentCurrent', subtitle:'Annual Rent (Proposed)'},
        {id:'firmTermRemain',name:'Firm Term Remaining', subId: 'firmTermAdded', subtitle:'(Current)'},
        {id:'maxTerm',name:'Max Available Term'},
        {id:'cash',name:'Cash Contribution'},
      ]
    }
  }

  dataForApprovalServiceEvent(item) {
    this.table = item;
    if(this.table) {
      this._pageEventDealsForApprovalList();
    }
  }

  private _pageEventDealsForApprovalList() {
    this.searchInput = '';
    this.isLoading = true;
    this.dealService
      .getAllForApprovalDeals(
        this.accountId,
        this.transaction.id,
        this.table.pageIndex + 1,
        this.table.pageSize,
        this.searchInput,
        this.table.sortParams,
        this.table.sortDirs
      )
      .pipe(finalize(() => (this.isLoading = false)))
      .subscribe({
        error: (err) => this.notificationService.showError(err),
        next: (res) => {
          this.table.data = res.items;
          console.log("this.table.forApprovalData" , res.items)
        },
        complete: noop,
      });
  }
}

#app-deals-transaction ts 代码

xport class DealsTransactionComponent implements OnInit {
  @Input() transactionId: any = 2;
  @Input() transactionName: string = '-';
  @ViewChild(TableMultiSortComponent, { static: true }) tableMultiSortComponent: TableMultiSortComponent;
  resetFormSubject: Subject<boolean> = new Subject<boolean>();
  tableOptions: any;
  @Input() transaction: any;
  totalDeals: number;

  isLoading: boolean;
  accountId: any;
  data: any;
  searchInput: string;
  table: any;
  constructor(
    private _snackBar: MatSnackBar,
    private dialog: MatDialog,
    private dealService: DealService,
    private notificationService: NotificationService,
    private route: Router,
    
  ) {}
  ngOnInit(): void {
    const currentAccountDetails = localStorage.getItem('currAcct') as any;
    if (currentAccountDetails) {
      this.accountId = JSON.parse(currentAccountDetails).accountId;
    }

    this.tableOptions = {
      columns:[
        {id:'name',name:'Deal Name',subId:'type', subtitle:'Deal Type'},
        {id:'annualRentProposed',name:'Annual Rent (Proposed)', subId: 'annualRentCurrent', subtitle:'Annual Rent (Proposed)'},
        {id:'firmTermRemain',name:'Firm Term Remaining', subId: 'firmTermAdded', subtitle:'(Current)'},
        {id:'maxTerm',name:'Max Available Term'},
        {id:'cash',name:'Cash Contribution'},
        {id:'action', name: 'Actions', actions:[
          {icon:'file_copy', name:'Copy', class:'primary-color' , },
          {icon:'delete', name: 'Delete', class:'mat-error'},
          {icon:'forward', name: 'For Approval', class:'primary-color' }
        ]}
      ]
    }
  }

  dealsServiceEvent(item) {
    this.table = item;
    if (this.table) {
      this._pageEventDealsList();
    }
  }
  public _pageEventDealsList() {
    this.searchInput = '';
    this.isLoading = true;
    this.dealService
      .getAllDeals(
        this.accountId,
        this.transaction.id,
        this.table.pageIndex + 1,
        this.table.pageSize,
        this.searchInput,
        this.table.sortParams,
        this.table.sortDirs
      )
      .pipe(finalize(() => (this.isLoading = false)))
      .subscribe({
        error: (err) => this.notificationService.showError(err),
        next: (res) => {
          this.table.totalItemCount = res.totalItemCount;
          this.table.lastItemOnPage = res.lastItemOnPage;
          this.totalDeals = res.items.length;
          this.table.data = res.items;
        },
        complete: noop,
      });
  }

#transactions-details.component 代码

<div class="tab-content">
    <app-deals-transaction *ngIf="tab === 'Deals'" [transaction]="transaction"
        ></app-deals-transaction>
</div>

#app 表多排序组件

@Component({
  selector: 'app-table-multi-sort',
  templateUrl: './table-multi-sort.component.html',
  styleUrls: ['./table-multi-sort.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush    
})
export class TableMultiSortComponent implements OnInit, OnChanges {
  @Input() tableOptions:any;
  @Input() tableData:any = [];
  @Input() isClientSide:boolean = false;
  @Input() isLoading: boolean = false;
  @Output() tableActionsEvent = new EventEmitter<any>();
  @Output() dataServiceEvent = new EventEmitter<any>() ;
  @ViewChild(MatMultiSort, { static: false }) sort: MatMultiSort;
  
  tableConfig: any = TABLE_MULTI_SORT_OPTIONS.DEFAULT;
  table:TableData<any>;
  displayedColumns: any;
  
  constructor() { }
  ngOnChanges(changes: SimpleChanges): void {
    console.log("changes" , changes)
  }

  ngOnInit(): void {   
    this.initTableMultiSort();
  }

  initTableMultiSort() {
    this.tableConfig = {
      ...this.tableConfig,
      ...this.tableOptions
    }
    
    this.table = new TableData<any>(this.tableConfig.columns,this.tableConfig.sortParams);
    this.table.pageSize = this.tableConfig.pageSize;
    this.table.pageIndex = this.tableConfig.pageIndex;
    this.table.nextObservable.subscribe(() => { this.getData(); });
    this.table.sortObservable.subscribe(() => { this.getData(); });
    this.table.previousObservable.subscribe(() => { this.getData(); });
    this.table.sizeObservable.subscribe(() => { this.getData(); });

    setTimeout(()=>{
      this.table.dataSource = new MatMultiSortTableDataSource(this.sort, this.isClientSide);
      this.getData();
    },0);
  }
  getData(){
    this.table.totalElements = 1;
    this.table.pageIndex = 0;
    this.table.pageSize = 10;
    this.table.data = this.tableData;

    if(this.dataServiceEvent) {
      this.dataServiceEvent.emit(this.table);
    }
  }

标签: javascriptangulartypescript

解决方案


有两种方法——

  • 在服务中创建一个变量并在组件之间共享它(如果您只想共享数据)
  • 在服务中创建 rxjs BehaviorSubject,根据用例在组件之间订阅和发送事件。

供参考链接


推荐阅读