Usually you inject Nav:NavController into your classes constructor to use it:
1
|
constructor
(
private
Nav
:
NavController
)
{
}
|
But if you are working in a service you will receive the following error:
1
|
No
provider
for
NavController
!
(
ExampleService
->
NavController
)
|
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
import
{
Injectable
}
from
'@angular/core'
;
import
{
NavController
,
App
}
from
"ionic-angular/index"
;
import
{
SetDetailPage
}
from
"../../pages/set-detail-page"
;
@
Injectable
(
)
export
class
ExampleService
{
private
nav
:
NavController
;
constructor
(
private
app
:
App
)
{
this
.
nav
=
app
.
getActiveNav
(
)
;
}
showAlert
(
)
{
this
.
nav
.
present
(
{
.
.
.
}
)
}
}
|
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.