我有一些带有一些服务的Nativescript + angular应用程序。当应用程序进入后台和前台时,一项服务需要做一些事情。
如何在应用程序生命周期事件上触发服务实例的功能?
这是我的主要内容。我在听生命周期事件:
import { platformNativeScriptDynamic } from "nativescript-angular/platform";
import { AppModule } from "./app.module";
import { on as applicationOn, suspendEvent, resumeEvent, ApplicationEventData } from "application";
applicationOn(suspendEvent, function (args: ApplicationEventData) {
//Trigger method performGoToBackgroundChecks of RemoteService
console.log("App goes to background");
});
applicationOn(resumeEvent, function (args: ApplicationEventData) {
//Trigger method performGoToForegroundChecks of RemoteService
console.log("App goes to foreground");
});
platformNativeScriptDynamic().bootstrapModule(AppModule);
以下代码来自remote.service.ts,只包含此问题的相关代码。该服务包含在不同页面中使用的逻辑。我想触发performGoToBackgroundChecks并执行GoToForegroundChecks。
import {Injectable} from "@angular/core";
@Injectable()
export class RemoteService {
public performGoToBackgroundChecks(){
}
public performGoToForegroundChecks(){
}
}
我还可以在remote.service.ts文件中添加应用程序生命周期事件处理程序,但我不知道如何访问服务实例以触发它的公共函数。
答案 0 :(得分:3)
正如mast3rd3mon指出的那样,我通过在需要它们的服务的构造函数中移动应用程序生命周期钩子来实现它。
这是我的RemoteService.ts工作代码:
import {Injectable} from "@angular/core";
import { on as applicationOn, suspendEvent, resumeEvent, ApplicationEventData } from "application";
@Injectable()
export class RemoteService {
constructor() {
applicationOn(suspendEvent, (args: ApplicationEventData) => {
this.performGoToBackgroundChecks();
});
applicationOn(resumeEvent, (args: ApplicationEventData)=> {
this.performGoToForegroundChecks();
});
}
public performGoToBackgroundChecks(){
console.log("in remoteService instance -- goto background");
}
public performGoToForegroundChecks(){
console.log("in remoteService instance -- goto foreground");
}
}