Ionic 2 - 从服务中的控制器调用函数



我有一个离子2项目,有一个页面home.html/home.ts和一个service connectivity-service.ts。该服务应检查用户是联机还是脱机。最重要的是,在服务中,添加了一些侦听器来监视用户是否脱机或联机。每个使用该服务的页面都应该为服务提供函数,这些函数应该在 onOnline/onOffline 上调用。

这是我的 connectivity-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中调用给定的函数?

您需要使用Function.Prototype.bind以确保this对象仍然是组件的对象。

this.platform.ready().then(() => {
this.connectivity.init(this.loadData.bind(this));//here
});

相关内容

  • 没有找到相关文章

最新更新