且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在ionic2/3中创建动态侧边导航菜单和子菜单

更新时间:2023-12-03 15:21:10

这是一个 工作示例一个>

首先,您需要一个提供商来保存您的菜单项.在上面的例子中:
app-service.ts

First, you need a provider to save your menu items. In the example above:
app-service.ts

import { Subject } from 'rxjs/Subject';

userId = 1; //this varible store your userId
menuItems = []; //this array store your menu items
menuSubject: Subject<string> = new Subject<string>(); //Here is the subject will broadcast an event whenever menu item change

//this function is called when you change the user
changeUser(userId) {
    this.userId = userId;
    //Get menu data from server then update your menu
     if(userId == 1){
        this.menuItems = [...] //See all code in the example above
     }
    this.menuSubject.next("new menu items have arrived");
  }

其次,在您的应用中显示菜单:
app.html:

Second, in your show the menu in your app:
app.html:

<ion-menu [content]="content" swipeEnabled="true" class="menu" type="reveal" width="100px">
  <ion-list>
    <ion-item class="menu-item" *ngFor="let item of menuItems" (click)="itemClick(item.component)">{{item.name}}</ion-item>
  </ion-list>
</ion-menu>
<ion-nav id="nav" #content [root]="rootPage"></ion-nav>

app.component.ts:

import { Platform, MenuController, App } from 'ionic-angular';
constructor(platform: Platform,
    private appService: AppService,
    private menuCtrl: MenuController){
    this.menuItems = this.appService.menuItems;
    //Subscribe whenever menu items changed
    this.appService.menuSubject.asObservable().subscribe(() => {
      this.menuItems = this.appService.menuItems;
      this.menuCtrl.open();
    })
}

//This function is called whenever menu item clicked
itemClick(component){
    this.rootPage = component;
}

最后,每当您更改用户(通过登录或任何您想要的)时,调用 appService 中的 changeUser 方法home.ts:

Finnally, whenever you change the user (by login or whatever you want), call the changeUser method in appService home.ts:

//See the full code in example
this.appService.changeUser(+userId);