Local notifications is a convenient way of keeping
the user informed without disturbing the actions of the user.
The notifications are put into the notification bar and will
be seen by the user when he or she wishes to.
Now, in NativeScript we can leverage
the NativeScript local notifications plug-in in order to
access the notifications capability on the mobile devices,
and put in notification into the notification bar.
In this exercise we will look at how we can leverage this to alert the user
whenever a dish is added to that list of favorites for the user.
This is a simple use case where I am demonstrating the use of local notifications.
You can leverage local notifications together with
server side push notifications in order to alert
users about events or actions that take place behind the scenes.
But in this case I will show you a simple way of
making use of local notifications in your application.
To make use of local notifications in your application
the first step is to install the NativeScript plugin.
So I type tns plugin add nativescript local notifications.
And let the plugin get installed.
Once the plugin is successfully installed then go to
your code and open favorite.service.ts file.
Going to our code.
Let me now open the favorite.service.ts file. And then in here.
First we will import * as localNotifications from 'nativescript-local-notifications.'
So we are importing all the exports from
the nativescript-local-notification NPM module into our application.
And then once that is done what we would like to do is
whenever we add an item to the list of favorites,
we want to deliver a local notification to the device.
So right there inside the addFavorite method
there let's leverage localNotifications.schedule.
So the schedule allows you to schedule a local notification.
The local notification has many options that are available.
You can schedule the notification to be delivered at a later time.
You can also configure various aspects of the local notification.
In this example I'm going to illustrate
a very simple way of leveraging the local notification.
And this has to be enclosed inside square brackets here.
So this is an array of objects that we are going to deliver here.
So inside here you will configure the JavaScript object with the
id as the id of the device that we are just adding to our list of favorites.
Then I will configure the title as favorites and
body as 'dish' + id + 'added successfully'.
We can also give the title as conFusion favorites to be more specific.
And this will return a promise to indicate whether the notification has been added or not.
So I will add that then.