@Simo,有点复杂。在 Cordova 中,您有一个事件“deviceready”,您可以使用它来控制事件暂停、恢复和后退按钮。
阅读官方文档,将 Web 应用程序转换为 movil 应用程序。
您可以看到 Cordova 将新事件添加到“文档”。 https://cordova.apache.org/docs/en/latest/cordova/events/events.html
那么如何将它添加到我们的 Angular 应用程序中?
对我来说,最好的方法是更改 AppComponent(主组件)以添加新事件并使用服务使所有流程透明。
在 AppComponent(主组件)的 AfterViewInit 中,我们将添加 document.addEventListener 用于准备、暂停、恢复和后退按钮
//we use a enum for the different events.
export enum CordovaEvent {BackButton,Resume,Pause}
export class AppComponent implements AfterViewInit{
constructor(private cordovaEventService:CordovaEventService) { }
ngAfterViewInit() {
document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
}
onDeviceReady() {
// Control pause, resume and backbutton
document.addEventListener('pause', this.onPause.bind(this), false);
document.addEventListener('resume', this.onResume.bind(this), false);
document.addEventListener("backbutton", this.onBackKeyDown.bind(this), false);
//a variable that I can use to know if is really a movil application
this.cordovaEventService.isCordoba=true;
};
onPause() {
//the only thing that I make is execute a function in a service
this.cordovaEventService.sendEvent(CordovaEvent.Pause);
};
onResume() {
this.cordovaEventService.sendEvent(CordovaEvent.Resume);
};
onBackKeyDown(e) {
this.cordovaEventService.sendEvent(CordovaEvent.BackButton);
e.preventDefault();
e.stopPropagation();
};
}
我们的服务非常简单。只是一个私有主题和一个可以订阅我们组件的 Observable。
@Injectable()
export class CordovaEventService {
private listeningSource:Subject<CordovaEvent>=new Subject<CordovaEvent>();
cordovaEvent:Observable<CordovaEvent>=this.listeningSource.asObservable();
isCordoba:boolean=false;
constructor() {
}
sendEvent(evento:CordovaEvent)
{
this.listeningSource.next(evento);
}
}
最后,任何组件都可以在ngOnInit中订阅cordovaEvent
ngOnInit() {
this.cordovaEventService.cordovaEvent.subscribe((evento: CordovaEvent) => {
if (evento == CordovaEvent.BackButton) {
this.ngZone.run(()=>{
....make something...
})
}
});
}