0

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?

2
  • What is Network? Why do you create a async function inside an async function? And why does the inner function return nothing? This code makes no sense to me, and is expected to not return the status. Commented Oct 20, 2024 at 15:57
  • The code is from capacitorjs.com/docs/apis/network and I will get the status somehow Commented Oct 20, 2024 at 17:57

1 Answer 1

0

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.