首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我们如何在Angular中访问ngOnInit上的output @Output?

我们如何在Angular中访问ngOnInit上的output @Output?
EN

Stack Overflow用户
提问于 2021-08-25 14:59:57
回答 2查看 213关注 0票数 0

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

感谢您的任何帮助或想法。致以问候。

#组件A ts代码

代码语言:javascript
运行
复制
     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代码

代码语言:javascript
运行
复制
 <app-table-multi-sort  (dataServiceEvent)="dataServiceEvent($event)" [tableOptions]="tableOptions" [tableData]="dealsListData" (tableActionsEvent)="tableActions($event)"></app-table-multi-sort>

#组件B代码- dataServiceEvent是此组件到组件A的输出

代码语言:javascript
运行
复制
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);
    }
  }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-08-25 15:34:37

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

代码语言:javascript
运行
复制
@ViewChild(TableMultiSortComponent, { static: true }) tableMultiSortComponent: TableMultiSortComponent;

然后,在组件A的ngOnInit方法中,您可以订阅组件B的dataServiceEvent EventEmitter (EventEmitter是RxJS主题的特例):

代码语言:javascript
运行
复制
// 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)));
  }

票数 0
EN

Stack Overflow用户

发布于 2021-08-25 15:30:12

您可以像这样处理事件和访问它的数据

组件A HTML代码:

代码语言:javascript
运行
复制
 <app-table-multi-sort  (dataServiceEvent)="dataServiceEvent($event)" [tableOptions]="tableOptions" [tableData]="dealsListData" (tableActionsEvent)="tableActions($event)"></app-table-multi-sort>

组件A TS文件:

代码语言:javascript
运行
复制
private _eventSubject$ = new Subject();

get eventData() {
   return this.eventSubject.asObservable();
}

ngOnInit(){
   this.eventData.subscribe((data) => {
      console.log(data)
  })
}

dataServiceEvent($event) {
   this._eventSubject$.next($event);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68925316

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档