我有一个带有一些服务的 Nativescript+Angular 应用程序。当应用程序转到后台和前台时,一项服务需要执行某些操作。
如何在应用程序生命周期事件上触发服务实例的函数?
这是我监听生命周期事件的 main.ts:
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和performGoToForegroundChecks。
import {Injectable} from "@angular/core";
@Injectable()
export class RemoteService {
public performGoToBackgroundChecks(){
}
public performGoToForegroundChecks(){
}
}
我还可以在remote.service.ts 文件中添加应用程序生命周期事件处理程序,但我不知道如何访问服务实例以触发其公共(public)函数。
最佳答案
正如 mast3rd3mon 指出的那样,我通过将应用程序生命周期 Hook 移动到需要它们的服务的构造函数内来使其工作。
这是我的 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");
}
}
关于angular - 如何从 Nativescript + Angular 中的应用程序生命周期事件触发服务功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47156319/