NativeScript handling back button event

后端 未结 4 495
别跟我提以往
别跟我提以往 2020-12-16 06:03

I am trying to handle the hardware back button in a NativeScript app. I am using NativeScript version 2.3.0 with Angular.

Here is what I have in main.ts

4条回答
  •  一向
    一向 (楼主)
    2020-12-16 06:40

    I'm using NativeScript with Angular as well and this seems to work quite nicely for me:

    import { RouterExtensions } from "nativescript-angular";
    import * as application from "tns-core-modules/application";
    import { AndroidApplication, AndroidActivityBackPressedEventData } from "tns-core-modules/application";
    
    export class HomeComponent implements OnInit {
      constructor(private router: Router) {}
        
      ngOnInit() {
        if (application.android) {
          application.android.on(AndroidApplication.activityBackPressedEvent, (data: AndroidActivityBackPressedEventData) => {
            if (this.router.isActive("/articles", false)) {
              data.cancel = true; // prevents default back button behavior
              this.logout();
            }
          });
        }
      }
    }
    

    Note that hooking into the backPressedEvent is a global thingy so you'll need to check the page you're on and act accordingly, per the example above.

提交回复
热议问题