Search code examples
nativescriptnativescript-angular

Nativescript, inject angular service within ios delegate


I'm using angular with nativescript and I would like to get some data from an api using an angular service within my project and push a local notification with that data. I would like to push this notification in the background using the example mentioned in the Nativescript's documentation

https://docs.nativescript.org/core-concepts/ios-runtime/how-to/BackgroundExecution.

The method looks like this:

import { LocalNotifications } from 'nativescript-local-notifications';

export class BackgroundRefreshAppDelegate extends UIResponder implements UIApplicationDelegate {
    public static ObjCProtocols = [UIApplicationDelegate];
    public static ObjCExposedMethods = {
        "runOnBackground": { returns: interop.types.void }
    };

    private bgTask;
    private timer;
    private timerCounter;

    public applicationPerformFetchWithCompletionHandler(application: UIApplication, completionHandler: any) {
        console.log('App is running in background');

        // Check for new data
        const newData = true;

        // If new data exists, initiate a local notification
        if (newData) {
            LocalNotifications.schedule([{
            title: 'test',
          }]).then(
              function() {
                console.log('Notification scheduled');
              },
              function(error) {
                console.log('scheduling error: ' + error);
              }
          );

            // Let the OS know that there were new data and complete the task
            completionHandler(UIBackgroundFetchResult.NewData)
        } else {
            // Otherwise, let the OS know there is no new data and complete the task
            completionHandler(UIBackgroundFetchResult.NoData);
        }

    }
}

How can I inject an angular service within this ios delegate and use it within applicationPerformFetchWithCompletionHandler method ?


Solution

  • You can not / shouldn't do that, background service run outside Angular context.

    Instead listen to a custom event on your service and trigger a custom event form your applicationPerformFetchWithCompletionHandler.