【问题标题】:Call function of page from service in ionic 4从 ionic 4 中的服务调用页面的功能
【发布时间】:2020-01-15 15:30:11
【问题描述】:

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

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

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

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

但是我得到一个错误

Circular dependency detected

【问题讨论】:

    标签: angular typescript ionic-framework


    【解决方案1】:

    在服务中:

      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() 都会被执行。

    【讨论】:

      【解决方案2】:

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

      如果服务实例被创建,那么你的 init 函数就会被调用

      app.module.tspage.module.ts

        providers: [
              ...
              YourService
            ], 
      

      【讨论】:

      • 问题是我也在将服务注入我的页面。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-27
      • 2015-08-25
      • 1970-01-01
      • 2015-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多