问题描述
我正在尝试处理 NativeScript 应用程序中的硬件后退按钮.我在 Angular 中使用 NativeScript 2.3.0 版.
I am trying to handle the hardware back button in a NativeScript app. I am using NativeScript version 2.3.0 with Angular.
这是我在 main.ts
文件中的内容
Here is what I have in main.ts
file
// this import should be first in order to load some required settings (like globals and reflect-metadata)
import { platformNativeScriptDynamic, NativeScriptModule } from "nativescript-angular/platform";
import { NgModule,Component,enableProdMode } from "@angular/core";
import { AppComponent } from "./app.component";
import { NativeScriptRouterModule } from "nativescript-angular/router";
import { routes, navigatableComponents } from "./app.routing";
import { secondComponent } from "./second.component";
import {AndroidApplication} from "application";
@Component({
selector: 'page-navigation-test',
template: `<page-router-outlet></page-router-outlet>`
})
export class PageNavigationApp {
}
@NgModule({
declarations: [AppComponent,PageNavigationApp,secondComponent
// ...navigatableComponents
],
bootstrap: [PageNavigationApp],
providers:[AndroidApplication],
imports: [NativeScriptModule,
NativeScriptRouterModule,
NativeScriptRouterModule.forRoot(routes)
],
})
class AppComponentModule {
constructor(private androidapplication:AndroidApplication){
this.androidapplication.on("activityBackPressed",()=>{
console.log("back pressed");
})
}
}
enableProdMode();
platformNativeScriptDynamic().bootstrapModule(AppComponentModule);
我正在使用
从应用程序"导入{AndroidApplication};
然后在 appComponentModule
的构造函数中,我正在为 activityBackPressed
注册事件,并且只执行 console.log.
Then in the constrouctor of appComponentModule
I am registering the event for activityBackPressed
and just doing a console.log.
这不起作用.
我在这里遗漏了什么?
推荐答案
我也在 Angular 中使用 NativeScript,这对我来说似乎很有效:
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();
}
});
}
}
}
请注意,挂钩 backPressedEvent 是全局性的,因此您需要根据上面的示例检查您所在的页面并采取相应措施.
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.
这篇关于NativeScript 处理后退按钮事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!