Ionic 4-禁用硬件后退按钮,然后将后退按钮启用为默认值

时间:2019-09-29 09:03:15

标签: angular ionic-framework

在某些情况下,我想禁用硬件后退按钮,之后我希望后退按钮充当默认按钮。

1 个答案:

答案 0 :(得分:1)

我对此issue的回答的参考

我发现了更好的方法来避免使用后退按钮设备,并在想要的任何页面上禁用后退

只需维修service.ts

import { Router, NavigationEnd } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class DisableBackService {
  // page disable back button
  private blackLists: string[] = ['/tab/wall', '/event-list', '/tutorial', '/offline-message'];

  constructor(private router: Router) {
    // call every have change page
    this.router.events.subscribe((ev) => {
      if (ev instanceof NavigationEnd) {
        const blackList = this.blackLists.find(el => ev.url.includes(el));
        if (blackList) {
          this.disableBack();
        } else {
          this.enableBack();
        }
      }
    });
  }

  private logger() {
    console.log('disable back button');
  }

  disableBack() {
    document.addEventListener('backbutton', this.logger, false);
  }

  enableBack() {
    document.removeEventListener('backbutton', this.logger, false);
  }
}