簡體   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