私はhome.html/home.tsページとservice connectivity-service.tsというページを持つionic 2プロジェクトを持っています。サービスは、ユーザーがオンラインかオフラインかをチェックする必要があります。そのサービスの上に、ユーザがオフラインになったりオンラインになったときに視聴するリスナーがいくつか追加されています。サービスを使用するすべてのページは、onOnline/onOfflineと呼ばれる機能をサービスに提供する必要があります。ここでイオン2 - サービス内のコントローラから呼び出す機能
は、接続-service.tsのための私のコードです:
import {Injectable} from '@angular/core';
import { Network } from 'ionic-native';
import { Platform } from 'ionic-angular';
declare var Connection;
@Injectable()
export class ConnectivityService {
onDevice: boolean;
onOnlineFunction: any;
onOfflineFunction: any;
constructor(public platform: Platform) {
this.onDevice = this.platform.is('cordova');
}
/**
* Initialise the connectivity service
* @param onOnlineFunction
* @param onOfflineFunction
*/
init(onOnlineFunction = null, onOfflineFunction = null){
this.onOnlineFunction = onOnlineFunction;
this.onOfflineFunction = onOfflineFunction;
if(this.isOnline()){
if(this.onOnlineFunction){
this.onOnlineFunction();
}
}
else{
if(this.onOfflineFunction){
this.onOfflineFunction();
}
}
this.addConnectivityListeners();
}
/**
* Check if the user is online
* @return {boolean}
*/
isOnline(): boolean {
// Check if the user is on a device or on browser
if(this.onDevice && Network.type){
return Network.type !== Connection.NONE;
}
else{
return navigator.onLine;
}
}
/**
* Watch online oberservable to check if the user comes online
* @return {Observable<any>}
*/
watchOnline(){
return Network.onConnect();
}
/**
* Watch offline oberservable to check if the user goes offline
* @return {Observable<any>}
*/
watchOffline() {
return Network.onDisconnect();
}
/**
* Add connectivity listeners to permanently check if the user goes on- or offline
*/
addConnectivityListeners(): void {
let onOnline =() => {
if(this.onOnlineFunction){
this.onOnlineFunction();
}
};
let onOffline =() => {
if(this.onOfflineFunction){
this.onOfflineFunction();
}
};
this.watchOnline().subscribe(() => {
onOnline();
});
this.watchOffline().subscribe(() => {
onOffline();
});
if(!this.onDevice){
document.addEventListener('online', onOnline, false);
document.addEventListener('offline', onOffline, false);
}
}
}
これは私のhome.tsでionViewDidLoad機能であり、ユーザーがオンラインのときに呼び出される関数は、/オンラインになる:
ionViewDidLoad() {
this.platform.ready().then(() => {
this.connectivity.init(this.loadData);
});
}
loadData(){
// Here are some API calls and other things with other services
// and also some allocations to some variables from home.ts
}
問題は、サービスがサービスの一部であるようにこの機能を呼び出すことです。したがって、この機能で使用されているサービスが接続サービスにインポートされない場合、機能していません。さらに、home.tsの変数への割り当ては機能していません。 home.tsで呼び出されたように、connectivity-service.tsで指定された関数を呼び出す方法がありますか?