6.2: Adding Alertify

Now, instead of console logging errors, we can add friendly notification popups if something goes wrong or if an action in successful.

We'll use a JavaScript library called AlertifyJS for this.

npm install alertifyjs --save

Adding Alertify CSS and JS files

In the .angular-cli.json file, first add the relative paths to the alertify CSS and alertify bootstrap CSS files into the styles array (order is important!):

"styles": [
    "../node_modules/alertifyjs/build/css/alertify.min.css",
    "../node_modules/alertifyjs/build/css/themes/bootstrap.min.css",
    "styles.scss"
],

Next, add the relative path to the alertify js file to the scripts array:

"scripts": [
    "../node_modules/alertifyjs/build/alertify.min.js"
],

Create a Service to Wrap Alertify Methods

Rather than use this as a global library, we'll wrap methods and features we're interested in in a service.

In the src/app/services folder, add a new service called alertify.service.ts

ng g s services/alertify --no-spec

First, just below the imports, add a new global variable called alertify:

declare let alertify: any;

Next, we'll provide wrapper methods to hold the alertify dialog messages:

export class AlertifyService {

  constructor() { }

  confirm(message: string, okCallback: () => any) {
    alertify.confirm(message, function(e) {
        if (e) {
            okCallback();
        } else {

        }
    });
  }

  success(message: string) {
      alertify.success(message);
  }

  error(message: string) {
      alertify.error(message);
  }

  warning(message: string) {
      alertify.warning(message);
  }

  message(message: string) {
      alertify.message(message);
  }

}

Import the AlertifyService into app.module.ts and add it to the providers array:

import { AlertifyService } from './services/alertify.service';

//  ...

providers: [
    AuthService,
    UserService,
    AuthGuard,
    MemberDetailResolver,
    MemberListResolver,
    ErrorInterceptorProvider,
    AlertifyService
],

Last updated