[英]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.ts
或page.module.ts
等模塊中的provider
數組中,然后在服務文件constructor
函數中調用this.mainService.init()
函數
如果創建了服務實例,則調用您的 init 函數
app.module.ts或page.module.ts
providers: [
...
YourService
],
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.