简体   繁体   中英

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();

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.

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

if service instance is create then your init function is called

app.module.ts or page.module.ts

  providers: [
        ...
        YourService
      ], 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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