angular - 如何从 Nativescript + Angular 中的应用程序生命周期事件触发服务功能

标签 angular nativescript

我有一个带有一些服务的 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/

相关文章:

Angular 2-使用 TypeScript 在一条路径中设置多个组件而不丢失数据的最佳方法是什么

java - 如何使用内容uri检查文件是否存在

NativeScript vue、vuex 和 urlhandler

angular - 当其他组件导致其数据更新并调用下一个时,Rx Observable 不更新

typescript - 如何添加使用动态组件加载器创建的组件的表单值?

angular - 任何减少 pdfmake 包大小的方法

angular - 在 ionic 输入中强制 2 个小数位精度

android - 两个插件之间的Nativescript冲突-Android Gradle

android - NativeScript 8.0.4 Android 应用程序图标不会更改默认设置

javascript - 然后在 nativescript 中获取后就无法工作