【问题标题】:Ionic side menu - trigger function in view.ts离子侧边菜单 - view.ts 中的触发功能
【发布时间】:2020-12-29 12:35:02
【问题描述】:

我在主app.component.html有一个菜单

<ion-app>
  <ion-split-pane contentId="main-content">
    <ion-menu contentId="main-content" type="overlay">
      <ion-content>
        <ion-list no-lines width="10">
          <ion-list-header>
            <h2>MyApp</h2>
          </ion-list-header>  
          <ion-menu-toggle auto-hide="true">
            <ion-item click='MainView.fooBar()'>
              Foo Bar
            </ion-item>
          </ion-menu-toggle>
    ....
    </ion-menu>
    <ion-router-outlet id="main-content"></ion-router-outlet>
  </ion-split-pane>
</ion-app>

我允许它在我的主视图中打开。该菜单在其他视图中被禁用。 现在,如何在我的菜单中触发单击事件,该事件将调用上述特定方法

class MainView implements OnInit {
 fooBar(){}
}

以某种方式通过路由器对象?我不明白,因为MainView 显示在 &lt;ion-router-outlet id="main-content"&gt;,整体在app.components中定义。

【问题讨论】:

  • 我需要从菜单中触发一个事件,该事件需要在 MainView 而不是 app.component.ts 中捕获。在 ionic3 中,我使用事件在视图之间进行通信,但这似乎已经消失了。
  • 就个人而言,我会将您的 fooBar() 方法从您的 MainView 组件中提取到服务中。但是,似乎有一种方法可以从外部父组件调用在&lt;router-outlet&gt; 内部呈现的组件方法。检查这个stackoverflow.com/questions/45949476/…
  • fooBar 在当前视图中做了一些 UI 工作,我应该添加...
  • 在某种程度上它就像一个远程过程调用,但在应用程序中。所以我喜欢 ionic3 中的事件库。
  • 当然,我明白了。就我个人而言,我会以不同的方式去做。我喜欢将大多数方法提取到服务中,这些服务可以操纵 observable 中保存的应用程序的状态。然后在你的视图组件中订阅这些 observables,你可以根据你的状态变化“做 UI 的事情”。

标签: angular ionic-framework ionic4 ionic5


【解决方案1】:

您可以根据自己的目的使用 ion-menu 事件。

Name              Description
ionDidClose       Emitted when the menu is closed.
ionDidOpen        Emitted when the menu is open.
ionWillClose      Emitted when the menu is about to be closed.
ionWillOpen       Emitted when the menu is about to be opened.

像这样。

<ion-menu (ionDidOpen)="foBar()" contentId="main-content" type="overlay">

打开侧边菜单时触发。

【讨论】:

    【解决方案2】:

    我通过编写自己的事件服务解决了这个问题

    import { Injectable } from '@angular/core';
    import { Subject, Observable } from 'rxjs';
    
    @Injectable({
        providedIn: 'root'
    })
    export class EventsService {
    
        static subject = new Subject<any>();
    
        static sendMessage(text){
            EventsService.subject.next(text);
        }
    
        static getMessage(): Observable<any>{
            return EventsService.subject.asObservable();
        }
    }
    

    其中一个视图 sendMessage 而另一个等待特定类型的 getMessage

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-01
      • 1970-01-01
      • 2015-07-29
      • 2014-09-06
      • 1970-01-01
      • 2020-05-27
      • 2014-12-31
      • 1970-01-01
      相关资源
      最近更新 更多