繁体   English   中英

离子 4 中从服务调用页面的功能

[英]Call function of page from service in ionic 4

我知道我可以从我的页面模块调用函数到我的服务。 但是,如何从我的服务调用一个函数到我的页面模块?

我尝试将页面导入到我的服务中

import { MainPage } from '../../pages/game/main/main.page';

然后调用函数this.mainService.init();

但是我收到了一个错误

Circular dependency detected

在服务中:

  private mySubject = new Subject<any>();
  ob = this.mySubject.asObservable();

  serviceFn(value:any) {
    this.mySubject.next(value);
  }

在组件中:

constructor(private myService:MyService){}
  ngOnInit()
  {
    this.myService.ob.subscribe((result) => {
          this.foo(result);
        }
      );
  }

  foo(result:any)
  {
    //access result here
  }

现在,无论何时调用 myService.serviceFn(argValue),都会执行组件中的函数 foo()。

您的服务包含在app.module.tspage.module.ts等模块中的provider数组中,然后在服务文件constructor函数中调用this.mainService.init()函数

如果创建了服务实例,则调用您的 init 函数

app.module.tspage.module.ts

  providers: [
        ...
        YourService
      ], 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM