Here is a quote from the official GitHub repository of the plugin:
The online event occurs when a device that was previously not connected to a network establishes a connection, allowing an application to access the Internet. This event relies on the same information as the Connection API and triggers when the connection type changes from NONE to any other value.
It is evident that the onConnect function will only emit data when a previously unconnected device connects to a network.
To check if the device is online during startup, you can directly check this.network.type
.
Alternatively,
You have the option to create a service that manages all of these functionalities:
@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');
}
You can then inject your service wherever needed and subscribe to the connection:
constructor(private myNetworkService: MyNetworkService) {
this.myNetworkService.connection.subscribe(type => {
// You may want to filter out null values
// Add .pipe(filter(type => type !== null)) before subscribing
})
}