我们如何在Angular的ngOnInit上访问输出@Output ?



我有从组件B到组件A的dataServiceEvent输出,我如何获得或访问组件A上的ngOnit中的dataServiceEvent数据?我可以在ngOinit外部作为函数访问它但我想在ngOnit内部访问它因为我想使用dataServiceEvent中的数据作为getListOfDeals的参数

谢谢你的任何帮助或想法。问候。

#组件A的代码

ngOnInit(): void {
//access the dataServiceEvent here
this.getListOfDeals()
}

// I can access it here but I want to access the data on ngOnInit
dataServiceEvent(item: any) {
this.tableElements = item;
// this.getListOfDeals();
}
private getListOfDeals() {
this.searchInput = '';
this.isLoading = true;
console.log("getting deals")
this.dealService
.getAllDeals(
this.accountId,
this.transaction.id,
this.tableElements.pageIndex + 1,
this.tableElements.pageSize,
this.searchInput,
this.tableElements.sortParams = ['name'],
this.tableElements.sortDirs = ['asc']
)
.pipe(finalize(() => (this.isLoading = false)))
.subscribe({
error: (err) => this.notificationService.showError(err),
next: (res) => {
// this.dealsListData[totalElements] = res.items.length;
this.dealsListData = res.totalItemCount;
this.dealsListData = res.lastItemOnPage;
this.dealsListData = res.items;
console.log('res', this.dealsListData);
},
complete: noop,
});
}

#组件A html代码

<app-table-multi-sort  (dataServiceEvent)="dataServiceEvent($event)" [tableOptions]="tableOptions" [tableData]="dealsListData" (tableActionsEvent)="tableActions($event)"></app-table-multi-sort>

#Component B code - dataServiceEvent是从这个组件到Component A的输出

export class TableMultiSortComponent implements OnInit {
@Output() dataServiceEvent = new EventEmitter<any>() ;
@Input() tableOptions:any;
@Input() tableData:any = [];
@Input() isClientSide:boolean = false;
@Input() isLoading: boolean = false;
@Output() tableActionsEvent = new EventEmitter<any>();
@ViewChild(MatMultiSort, { static: false }) sort: MatMultiSort;

tableConfig: any = TABLE_MULTI_SORT_OPTIONS.DEFAULT;
table:TableData<any>;
displayedColumns: any;

constructor() { }
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);

}
ngOnChanges(changes: SimpleChanges) {   
if (changes.tableData && changes.tableData.currentValue){  
this.initTableMultiSort()
}
}
getData(){
//Todo: get totalelement, pageindex, pagesize from api service response
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);
}
}

你可以在组件a的typescript中定义一个用@ViewChild装饰的属性来获取组件B的引用(注意:ViewChild的'static'属性是在Angular 8中引入的):

@ViewChild(TableMultiSortComponent, { static: true }) tableMultiSortComponent: TableMultiSortComponent;

然后,在组件A的ngOnInit方法中,你可以订阅组件B的dataServiceEvent EventEmitter (EventEmitter是RxJS Subject的一个特殊情况):

// This property is used as the notifier of the takeUntil operator to prevent memory leaks in your code:
private _destroyed$ = new Subject();
ngOnInit() {
this.tableMultiSortComponent.dataServiceEvent
.pipe(
// switchMap subscribes to a new call everytime dataServiceEvent emits an event, and cancels previous calls, if any - You can use another RxJS higher order mapping operator depending on your needs (check: https://blog.angular-university.io/rxjs-higher-order-mapping/):
switchMap((event) => this.getListOfDeals(event)),
// The takeUntil operator is useful to destroy the subscription to avoid memory leaks once the component gets destroyed, you can use it for other subscriptions as well
takeUntil(this._destroyed$)
)
// The subscribe was moved here from the 'getListOfDeals' method
.subscribe({
error: (err) => this.notificationService.showError(err),
next: (res) => {
// this.dealsListData[totalElements] = res.items.length;
this.dealsListData = res.totalItemCount;
this.dealsListData = res.lastItemOnPage;
this.dealsListData = res.items;
console.log('res', this.dealsListData);
},
complete: noop,
});
}
ngOnDestroy() {
this._destroyed$.next();
this._destroyed$.complete();
}
// In order to work with the subscription in the ngOnInit, here you must pass a parameter, which is the value emitted by the dataServiceEvent EventEmitter and change the method accordingly (I tried to understand it from your previous code, changing 'this.tableElements' with the 'item' parameter):
private getListOfDeals(item) {
this.searchInput = '';
this.isLoading = true;
console.log("getting deals")
return this.dealService
.getAllDeals(
this.accountId,
this.transaction.id,
item.pageIndex + 1,
item.pageSize,
this.searchInput,
item.sortParams = ['name'],
item.sortDirs = ['asc']
)
.pipe(finalize(() => (this.isLoading = false)));
}

您可以像这样处理事件并访问其数据

组件A HTML代码:

<app-table-multi-sort  (dataServiceEvent)="dataServiceEvent($event)" [tableOptions]="tableOptions" [tableData]="dealsListData" (tableActionsEvent)="tableActions($event)"></app-table-multi-sort>

组件A TS文件:

private _eventSubject$ = new Subject();
get eventData() {
return this.eventSubject.asObservable();
}
ngOnInit(){
this.eventData.subscribe((data) => {
console.log(data)
})
}
dataServiceEvent($event) {
this._eventSubject$.next($event);
}

最新更新