问题
How to access a method from the app component to main.ts file??
I am developing android and ios mobile application using Nativescript angular. I have created a ios delegate class for application onResume. I want to call the native script class component method inside of my ios delegate class. Help me achieve the functionality
My ios delegate class:
import { android, ios, AndroidApplication, AndroidActivityBundleEventData } from "tns-core-modules/application";
import * as application from "tns-core-modules/application";
class MyDelegate1 extends UIResponder implements UIApplicationDelegate{
constructor(private sharedClass:sharedClass) {
super();
}
public static ObjCProtocols =[UIApplicationDelegate];
applicationWillEnterForeground(application:UIApplication):void{
application.notify({
eventName:"SampleFunction",
object:application
})
}
applicationDidEnterBackground(application:UIApplication):void{
console.log("applicationDidEnterBackground"+application);
}
}
My nativescript component class
import { Component, OnInit } from "@angular/core";
export class AppComponent implements OnInit {
constructor(){}
ngOnInit(){ }
SampleFunction(){
console.log("Will call from ios delegate class");
}
}
Help me to fix this issue.
回答1:
You are not suppose to call the Component method directly from your delegate. A better practice would be, firing an event on application object and listening to the same form your Angular component.
FYI, events like pause / resume are supported out of the box.
Edit:
To fire event on application module,
import * as application from "tns-core-modules/application";
applicationWillEnterForeground(application:UIApplication):void{
application.notify({
eventName: "YourEventName",
object: application,
// Add any additional params that can be accessed from the event object by listener callback
});
}
回答2:
ViewChild might be one of the ways you are looking for.
In your app.component.ts,
import {ViewChild} from "@angular/core";
export class AppComponent{
@ViewChild('templateReferenceVariableName') reference : YourComponent;
reference.methodYouWantedToAccess();
}
In your app.component.html,
<html>
<your-component #templateReferenceVariableName > </your-component>
</html>
The #templateReferenceVariableName acts a the link between the .ts and .html
P.S: you can replace the name with your like.
来源:https://stackoverflow.com/questions/57955129/how-to-access-component-method-inside-my-ios-delegate-class