June 20, 2016

Ionic 2 use NavController in Service to show Alerts

Usually you inject Nav:NavController into your classes constructor to use it:

But if you are working in a service you will receive the following error:

If you want to show alerts from within a service you are required to use the NavController.  To do so simply create the private field nav with type NavController. Then use the app.getActiveNav method provided by ionic-angular. See the snippet below for a full example:

Now you can show dialogs and alerts from a service in Ionic 2. But keep in mind, this is not good practice – services should not be tied to the UI of your application.

Related Posts

Can Kattwinkel
Developer at thecodecampus </>

10 responses to “Ionic 2 use NavController in Service to show Alerts”

  1. Alugbin Abiodun says:

    Please can we get the javascript version?? it keeps giving no provider for App!!

  2. Can Kattwinkel says:

    Hello Alugbin Abiodun,

    first of all – developing a Ionic 2 app with JavaScript is a BIG mistake. Take 3 days to learn the necessary TypeScript it will save you way more time.

    However you should be able to use app.getActiveNav(); in JavaScript as well, just follow the imports in the code snippet. I couldn’t setup a JavaScript App with ionic since the startup repositories are now fully in TypeScript.

  3. Brock Ellis says:

    Hi there!

    This blog post was very helpful!

    I have an ErrorService that I was using to catch errors thorough the application and display an alert. I know that this is bad practice (as stated by many other blogs as well) but I have never seen a good example of error handling and display?

    Where should the error UI (AlertController and such) go? How could you set up a global error class to be reusable between all components, if that’s even possible.

    Thanks so much for your help!

  4. Venkata says:

    The nav.present method I do not see in the ionic2 now. was that removed?
    Can you please explain any other way I can do that?

  5. Thanks man, it worked here!

  6. Chikku says:

    Thank you great explanation!

  7. Andrey says:

    Thank you so much! This is solution for my problem!

  8. zuan says:

    Thank you for the useful update For beginners and start your career in Ionic.

  9. shreyaz says:

    Thanks for giving error and nav controller code. These code are usefull ionic developer.

Leave a Reply

Add code to your comment in Markdown syntax.
Like this:
`inline example`

code block

Your email address will not be published.