首页 > 解决方案 > 如何在 Ionic 的应用程序组件中触发自定义事件?

问题描述

ionic项目中,我想更改变量showSearchBox dynamically,这就是原因。我使用了一个searchBox由另一个组件触发但searchBoxShow()从未调用过的自定义事件。那么我该如何解决这个问题,以便我可以动态触发一个函数,该函数app.component将动态更新变量searchBox

这是我的app.component.html代码。

<ion-app>
  <ion-router-outlet style="margin-top: 50px; bottom: 0px;" *ngIf="showSearchBox" (searchBox)="searchBoxShow()"></ion-router-outlet>
  <ion-router-outlet *ngIf="!showSearchBox" (searchBox)="searchBoxShow()" ></ion-router-outlet>
</ion-app>

以及other.component.ts.

@Output('searchBox') showSearchBox = new EventEmitter();

ionViewDidEnter() {
  this.showSearchBox.emit();
}

标签: ionic-frameworkionic4router-outlet

解决方案


创建事件服务。在 EventService.ts 中:

    export class EventService {
    private dataObserved = new BehaviorSubject<any>('');
    currentEvent = this.dataObserved.asObservable();
    constructo(){}

    publish(param):void {
      this.dataObserved.next(param);
    }
   }

从示例 page1 发布事件:

    constructor(public eventService:EventService){}
updatePost(value){
this.eventService.publish('show:searchbar');
} 

在 app.component.ts 中:

constructor(public eventService:EventService){
  eventService.currentEvent.subscribe(value=>{
if(value=='show:searchbar'){
//do something eachtime event is emited
}   
});
}

推荐阅读