I use this service class in order to get the network status:
@Injectable()
export class NetworkConnectionService {
constructor() {
}
addNetworkConnectionListener() {
Network.addListener('networkStatusChange', status => {
console.log('Network status changed', status);
});
}
getCurrentNetworkStatus() {
const self = this;
const currentNetworkStatus = async () => {
const status = await Network.getStatus();
};
return currentNetworkStatus;
}
}
and I want to get the status string in order to print it in html. How do I get this string?
You should make your getCurrentNetworkStatus()
async, because Network.getStatus()
is asynchronous (it returns a Promise). Also instead of creating an additional function, you should stick to one function, the additional function doesn't bring any value. One additional thing that needs to be fixed is that await Network.getStatus();
returns an object, and you need to access its connectionType
property.
async getCurrentNetworkStatus() {
const status = await Network.getStatus();
return status.connectionType;
}
Now you have a function which returns a Promise holding a string. In your component, make sure to inject the service and that it's public
, so it can be used in the template:
export class YourComponent {
public networkConnectionService = inject(NetworkConnectionService);
}
Last step: Use the async
pipe in the template to unwrap the string from the promise:
<p>
Network status:
{{ networkConnectionService.getCurrentNetworkStatus() | async }}
</p>