在线事件在先前未连接的设备收到以下消息时触发
网络连接,以允许应用程序访问Internet.它
依赖于与Connection API相同的信息,并在出现以下情况时触发
connection.type从NONE更改为任何其他值.
The online event fires when a previously unconnected device receives a
network connection to allow an application access to the Internet. It
relies on the same information as the Connection API, and fires when
the connection.type changes from NONE to any other value.
如您所见,onConnect仅在以前未连接的设备接收到网络连接时才会发出信号.
As you can see onConnect will only emit something when previously unconnected device receives a network connection.
要在启动时检查设备是否在线,可以直接检查this.network.type
To check on startup if device is online you can directly check this.network.type
或
您可以创建将处理所有这些问题的服务
You can create a service which will handle all these
@Injectable()
export class MyNetworkService implements OnInit {
public connection: BehaviorSubject<string> = new BehaviorSubject(null);
constructor(private network: Network, private platform: Platform) {
this.connection = this.network.type;
this.platform.ready().then(() => {
this.network.onConnect().subscribe(() => {
this.connection = 'something';
});
this.network.onDisconnect().subscribe(() => {
this.connection = 'none';
});
});
}
ngOnInit() {
this._setCurrentConnectionType();
this.platform.ready().then(() => {
this.network.onConnect().pipe(timer(3000)).subscribe(this._onConnectHandler);
this.network.onDisconnect().pipe(timer(3000)).subscribe(this._onDisconnectHandler);
});
}
private _onConnectHandler= () => this.connection.next(this.network.type);
private _onDisconnectHandler = () => this.connection.next('offline');
}
然后您可以将服务注入到任何地方,并订阅连接.
And then you can inject your service where-ever you want and subscribe to connection.
constructor(private myNetworkService: MyNetworkService) {
this.myNetworkService.connection.subscribe(type => {
// you might filter out nulls
// Before subscribe add .pipe(filter(type => type !== null))
})
}