Accessing Angular service from a Java class extend

android

#1

I followed this to get an Android background service working.

android.service.autofill.AutofillService.extend("com.tns.myapp.AutofillService", {
   onFillRequest() {
      console.log('can run js');
   }
}

I’d like to access some existing Angular services. However I’m unsure how. The java class is not an Injectable so I cannot access them in the typical manner from the constructor.

One method I found was this

bootstrap(AppComponent, [FooService]).then((appRef) => {
    injector = appRef.injector;
});

and then reference the injector object later. However, unlike regular Angular, in Nativescript the bootstrapModule does not return a Promise.

Is there another way to reference the an Angular service from inside the Java class?


#2

I think accessing Angular service from a background service is not a good idea. Your background service is meant to run even if your app is not foreground (which means Angular is not running at all). I don’t think its wise to initiate Angular, create a service instance only to call a web service.

You may use the Http package from core modules to communicate with your server when you do it from a background service, create a utility singleton class that can be used from background service and from Angular service to process the data fetched, so you still share the logic for processing data but just the effort for invoking the api is duplicated.


#3

Thanks for responding.

accessing Angular service from a background service is not a good idea.

I found a method that let me access the entire angular app - and it crashes when I close my main app but try to use the autofill service. So you are correct - I’m glad to have some definitive evidence of how this works too.

The service utilizes a reasonably complex portion of the app. I think I can try to manually inject the services I need without the entire angular app. This unfortunately is awkward. This code works in the service even when the main app is closed:

const injector = Injector.create([{provide: A, useClass: A, deps: []}]); 
const a = injector.get(A);
console.log('service', a.something);

I’m still unsure if I’m abusing Injector or making things harder for myself. Is there a better way to access HttpClient than using Injector? I don’t need the full angular app - but I’d love to reuse some HTTP related services and some NGRX things. I’ll see how awkward this is and at some point will consider removing angular.