[英]Call function of page from service in ionic 4
I know I can call functions from my page module to my service.我知道我可以从我的页面模块调用函数到我的服务。 However how can I call a function from my service TO my page module?但是,如何从我的服务调用一个函数到我的页面模块?
I tried importing the page into my service我尝试将页面导入到我的服务中
import { MainPage } from '../../pages/game/main/main.page';
and then calling the function this.mainService.init();
然后调用函数this.mainService.init();
however i am getting an error of但是我收到了一个错误
Circular dependency detected
In the service:在服务中:
private mySubject = new Subject<any>();
ob = this.mySubject.asObservable();
serviceFn(value:any) {
this.mySubject.next(value);
}
In the component:在组件中:
constructor(private myService:MyService){}
ngOnInit()
{
this.myService.ob.subscribe((result) => {
this.foo(result);
}
);
}
foo(result:any)
{
//access result here
}
Now whenever you call myService.serviceFn(argValue), function foo() in the component will be executed.现在,无论何时调用 myService.serviceFn(argValue),都会执行组件中的函数 foo()。
your service include in provider
array in module like app.module.ts
or page.module.ts
then after call this.mainService.init()
function in service file constructor
您的服务包含在app.module.ts
或page.module.ts
等模块中的provider
数组中,然后在服务文件constructor
函数中调用this.mainService.init()
函数
if service instance is create then your init function is called如果创建了服务实例,则调用您的 init 函数
app.module.ts or page.module.ts app.module.ts或page.module.ts
providers: [
...
YourService
],
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.