Giter Site home page Giter Site logo

flauc / angular2-notifications Goto Github PK

View Code? Open in Web Editor NEW
743.0 26.0 167.0 4 MB

A light and easy to use notifications library for Angular.

Home Page: https://stackblitz.com/edit/angular2-notifications-example

License: MIT License

TypeScript 81.11% HTML 5.94% CSS 10.70% JavaScript 2.25%
angular2 notifications toasts

angular2-notifications's Introduction

Angular2-Notifications

A light and easy to use notifications library for Angular 2. It features both regular page notifications (toasts) and push notifications.

Build Status NPM Version NPM Downloads

Push Notifications have been moved to a separate library ng-push

Table of Contents

Example

Take a look at the live demo here: Live Demo

Setup

Install the library

npm install --save angular2-notifications
# Or using Yarn for a faster installation
yarn add angular2-notifications

SystemJS

Map the library in your system.config.js if you're using SystemJs.

var map = {
    'angular2-notifications': 'node_modules/angular2-notifications'
}

var packages = {
    'angular2-notifications': { main: './dist/index.js', defaultExtension: 'js' }
}

Webpack

If you're using Webpack >= 2, just include the library in your main.ts or vendor.ts file

import 'angular2-notifications';

Setup

Import the SimpleNotificationsModule in to your root AppModule (it will not work if you try to import it into a shared module)

import { SimpleNotificationsModule } from 'angular2-notifications';

@NgModule({
    imports: [
        BrowserModule,
        // Animations need to be imported in to your project to use the library
        BrowserAnimationsModule, 
        SimpleNotificationsModule.forRoot()
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule { }

Add the SimpleNotificationsComponent in to the component where you want to use the notifications. Or in your top level component for use in child components.

...
template: '<simple-notifications></simple-notifications>'
...

You will also need to use the NotificationsService in your component to create or remove the notifications.

...
constructor( private _service: NotificationsService ) {}
...

The create and destroy Event Emitters emit the notification that was created or destroyed you can utilise this functionality like this:

<simple-notifications [options]="options" (create)="created($event)" (destroy)="destroyed($event)"></simple-notifications>

If your app cannot find the built JS files for this package, you may need to tell your build script to scan the angular2-notifications directory. See the related issue #25. Example:

'angular2-notifications/*.+(js|js.map)',
'angular2-notifications/lib/*.+(js|js.map)'

Creating Notifications

This are the currently available access methods:

  • The access methods return the constructed notification along with the created id.
Method Description
success(title: any, content?: any, override?: any, context?: any) Creates a success notification with the provided title and content.
error(title: any, content?: any, override?: any, context?: any) Creates an error notification with the provided title and content.
alert(title: any, content?: any, override?: any, context?: any) Creates an alert notification with the provided title and content.
warn(title: any, content?: any, override?: any, context?: any) Creates a warn notification with the provided title and content.
info(title: any, content?: any, override?: any, context?: any) Creates an info notification with the provided title and content.
bare(title: any, content?: any, override?: any, context?: any) Creates a bare notification with the provided title and content. This notification type is best used when adding custom html.
create(title: any, content: any = '', type: string = 'success', override?: any, context?: any) Use this method to create any notification type ['success', 'error', 'alert', 'info', 'bare'].
html(html: any, type: string = 'success', override?: any, icon: string = 'bare', context?: any) Use this method to create a notification with custom html. By specifying an icon (success, error, alert, info or warn) you can use the default icons in addition to your custom html. If you do not explicitly pass an icon param no icon will be shown by default.
remove(id?: string) Removes the notification that has the provided id or removes all currently open notifications if no id was provided.

The title, content and html arguments can be a string, html string or TemplateRef. Now it's also possible to pass the datas (context) to the TemplateRef by using the optional context argument.

Example using TemplateRef

To use a TemplateRef in the title or content you need to create it in a component template:

<ng-template #example let-title="title">
    <p>{{title}}</p>
</ng-template>

Then you need to somehow get it to the component:

  title: string = 'Winter is coming';
  @ViewChild('example') example: TemplateRef<any>;

  open() {
    let context: any = {title: this.title};
    this._service.html(this.example, null, null, null, context);
  }

You could also pass the template through the open() method:

    open(temp: TemplateRef<any>) {
        this._service.html(temp, null, null, null, context);
    }

Subscribing to clicks

If you are interested in the clicks that happen on a notification you have the possibility to subscribe to a EventEmitter. The methods (success, error, alert, warn, info, bare, create and html) from the NotificationsService return an Object of type Notification.

const toast = this.notificationsService.success('Item created!', 'Click to undo...', {
      timeOut: 3000,
      showProgressBar: true,
      pauseOnHover: true,
      clickToClose: true
    });

The returned object has a click property with an EventEmitter on it which you can subscribe to. Your callback then gets notified with the click event at each click that happens on your Notification.

toast.click.subscribe((event) => {
    doSomething(event)
});

If you have configured the notification to close when the icon is clicked, an EventEmitter exists to listen for those clicks as well.

const toast = this.notificationsService.success('Item created!', 'Click to undo...', {
      timeOut: 3000,
      showProgressBar: true,
      pauseOnHover: true,
      clickToClose: false,
      clickIconToClose: true
    });

With the corresponding clickIcon property as above.

toast.clickIcon.subscribe((event) => {
    doSomething(event)
});

Options

Global options can be added in two ways. They can be passed through the forRoot() method on the module.

SimpleNotificationsModule.forRoot({
    ...options
})

You can also pass them in to the root component.

<simple-notifications [options]="options"></simple-notifications>

This are the current options that can be set globally:

Option Type Default Description
position ["top" or "bottom" or "middle", "right" or "left" or "center"] ["bottom", "right"] Set the position on the screen where the notifications should display. Pass an array with two values example: ["top", "left"].
timeOut int 0 Determine how long a notification should wait before closing. If set to 0 a notification won't close it self.
showProgressBar boolean true Determine if a progress bar should be shown or not.
pauseOnHover boolean true Determines if the timeOut should be paused when the notification is hovered.
lastOnBottom boolean true Determines if new notifications should appear at the bottom or top of the list.
clickToClose boolean true Determines if notifications should close on click.
clickIconToClose boolean false Determines if notifications should close when user clicks the icon.
maxLength int 0 Set the maximum allowed length of the content string. If set to 0 or not defined there is no maximum length.
maxStack int 8 Set the maximum number of notifications that can be on the screen at once.
preventDuplicates boolean false If true prevents duplicates of open notifications.
preventLastDuplicates boolean or string false If set to "all" prevents duplicates of the latest notification shown ( even if it isn't on screen any more ). If set to "visible" only prevents duplicates of the last created notification if the notification is currently visible.
theClass string null A class that should be attached to the notification. (It doesn't exactly get attached to the selector but to the first div of the template.)
rtl boolean false Adds the class .rtl-mode to the notification aligning the icon to the left and adding direction: rtl
animate "fade" or "fromTop" or "fromRight" or "fromBottom" or "fromLeft" or "scale" or "rotate" or null "fromRight" Choose the type of animation or set the value to null not to display animations.
icons Icons DefaultIcons Overrides the default icons

Icons

Option Type Default Description
alert string Clock html string for alert icon
error string Exclamation Point html string for alert icon
info string Info html string for alert icon
warn string Warning html string for warning icon
success string Check html string for alert icon

Here is an example of passing the options to the component. You only pass the options you want changed. Options passed to the component are global. They apply to all of the notifications the get created.

...
template: '<simple-notifications [options]="options"></simple-notifications>'
...
public options = {
    position: ["bottom", "left"],
    timeOut: 5000,
    lastOnBottom: true
    ...
}

If you want a specific notification to have different options you can override them when calling any of the access methods by passing them to the override object. The following options can be overridden:

  • id
  • animate
  • timeOut
  • showProgressBar
  • pauseOnHover
  • clickToClose
  • clickIconToClose
  • maxLength
  • theClass
  • icon

This is an example of overriding global options:

this._notificationsService.success(
    'Some Title',
    'Some Content',
    {
        timeOut: 5000,
        showProgressBar: true,
        pauseOnHover: false,
        clickToClose: false,
        maxLength: 10
    }
)

Development

To generate all *.js, *.d.ts and *.metadata.json files:

$ npm run build

To lint all *.ts files:

$ npm run lint

License

MIT © Filip Lauc

angular2-notifications's People

Contributors

a-sh avatar alippai avatar andreasonny83 avatar armno avatar asnelling avatar blackholegalaxy avatar boban100janovski avatar bokzor avatar caballerog avatar ccreighton-apptio avatar deadlydoll avatar dependabot[bot] avatar flauc avatar guerric-p avatar guerricphalippou avatar hicham-barhoumi avatar hoangnguyenba avatar it-ideas avatar jaybekster avatar jbouzekri avatar kreuzerk avatar krojew avatar lbrooks-liquidnet avatar menno-sn avatar mkollers avatar netstart avatar notprathap avatar ottunger avatar shibulijack avatar sialcasa avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

angular2-notifications's Issues

npm module references src folder

I tried to use the npm module in the Webpack project and it runs into the issue of the .map files referencing the src folder. I was able to workaround with copying the src folder from github and placing it in the node_module installation of angular2-notifications. It would be great if you could fix it.

HTML notifications are always viewed as equal

I'm setting
preventDuplicates: true, preventLastDuplicates: true

But when i create two notifications that are html notifications, with different html, only the first is shown.
Taking a quick look at src/simpleNotifications.component.ts, it appears that the html property is not used when seeing if two notifications are equal.

Getting 404 error

I want to use this library, but I'm getting the following error: Error: Error: XHR error (404 Not Found) loading http://localhost:8000/angular2-notifications(…)

It says 404 not found, but when I click on NotificationsService in my IDE then it goes to the declaration.

Also I did followed your example. Here is my commit where you can see that I had followed your example:
superzaky/node-portfolio-zaky@9ff7b4d

Am I missing something or am I doing something wrong?

Notification is not floating on screen

If my browser is not scrolled to the bottom of the web page, I can't see the notifications.

The noficiation is not working as "fixed" in my app, although it works fine in the provided demoe.

What can cause it to happen?

Custom button action in notification

I tried the following code:

this._service.html('Are you sure?<br/><button md-button (click)="freeUser()">Yes</button>',"info");

Unfortunetly the click event not working, so my question is, if there is any way to make custom button with some action in a notification body?

possibility to remove a specific notification's popup

Hi, thanks for your efforts.
It would be great if I can remove a specific popup after it's displayed, like:

successId = this._notificationsService.success(
    title: 'example', 
    content:'example', 
    override: {
        timeOut: 5000,
        showProgressBar: true,
        pauseOnHover: false,
        clickToClose: false,
        maxLength: 10
    }
);
// do some stuff
// then when I need to close it:
this._notificationsService.close(successID);

Notification Singleton use

Hello,
It's not a problem, I just want an information, It's possible to include : SimpleNotificationsComponent in AppComponent in order to use them for all child AppComponent?

Because, currently when I want to use notification, I must include in all child template :
<simple-notifications [options]="options"></simple-notifications>

Thanks for advice

example clickToClose not working

Hi

I cloned the project and ran the example locally. I can create the notifications but clicking on them doesn't close it.

Am I missing something?

Thanks

TypeError: el.createShadowRoot is not a function

Hi,

I'm trying to use your plugin in an Ionic 2 app.

Unfortunately, I get a TypeError: el.createShadowRoot is not a function

I searched on this and found this link that talk about EncapsulationViewand I saw that you recently introduce this in your code.

So I tried to use it for my @page component but same thing happened.

If I remove the directives: [NotificationsComponent] the error disappears but the notifications don't work.

So I'm not sure if the issue is related to this library or the ionic framework..

PS :
In the readme, it says directives: [NotificationComponent] and in sample it's directives: [NotificationsComponent] so it could be helpful to rename the class as @sialcasa suggested.

UPDATE :
With ViewEncapsulation.Native, I get a blank page with previous error in Firefox and Safari. For Chrome, my page is displayed with broken CSS and I get a TypeError: Cannot convert undefined or null to object in [ {{ "pick_photo_button" | translate }}.
With ViewEncapsulation.Emulated, all 3 browsers displays the previous Chrome behavior.

So apparently, there is a conflict with ng2-translate plugin too.

Not sure if it's all clear..

Missing main file in package.json

Dear Filip!

Please set the main property in the package.json file ("main": "./components.js") to be able to use it with webpack properly.

Thanks!

Awesome library by the way. 👍

Method inside the method

Hello Filip, i tried your noti noti, and i called method inside method from the method by clicking in the method to get the method.

Can you help me?

Misbehaving notifications

Hi,

I am trying to implement your package in the angular 2 seed project and firing the this._service.success('A notification', 'Something you should know...'); code. I am noticing that the notifications are misbehaving:

  • the notifications do not disappear when the timeout elapses
  • the close on click does not work
  • new notifications keep getting triggered when the timeout of the last one finishes or I click on an existing one

I have tried replicating the cod in your example as closely as possible. The only difference is that I have not needed to map the libray. The seed is using System.JS but the configuration is in the config.ts file.
I have added a link to a project that reproduces the problem. Any insights would be greatly helpful.

https://www.dropbox.com/s/biui2ngo7xt3cex/notification-test.zip?dl=0

Error with Karma

In our main systemjs config we're getting an "export undefined" error.

System.config({
baseURL: '/base/',
defaultJSExtensions: true,
paths: {
'angular2/': 'node_modules/angular2/.js',
'rxjs/': 'node_modules/rxjs/.js',
'moment': 'node_modules/moment/moment.js',
'braintree': 'node_modules/braintree-web/dist/braintree.js',
'ng2-bootstrap/': 'node_modules/ng2-bootstrap/.js',
'angulartics2/': 'node_modules/angulartics2/.js',
},
map: {
'angular2-notifications/*': 'node_modules/angular2-notifications'
}
});

When we don't include this map property, it works. However - Karma stops working and gives an error:

04 04 2016 17:24:00.019:WARN [web-server]: 404: /base/angular2-notifications/components.js

Any help much appreciated!

Cannot read property 'unsubscribe' of undefined

I use authorization component which checks if user is authorize to see protected page where I have and SimpleNotificationsComponent. In case of unauthorized attempt, the authorization component uses Router and navigates to login page. And in that case I got:

Unhandled promise rejection TypeError: Cannot read property 'unsubscribe' of undefined(…)

which leads to NotificationComponent and:

ngOnDestroy() { this.listener.unsubscribe() }

It is probably because of component not being initializes in ngOnInit.

exports is not defined

I am using this lib in my app but its not working is shows this error
exports is not defined
how can I fix it? I have no clue about it.
I am using Angular 2 rc-4

Unable to build the library

Hi, I just cloned the lib and tried to npm run build, I get the following error:

error-ng2-notifications

λ npm run build

[email protected] build C:\Users\Abdel\Desktop\angular2-notifications
tsc

node_modules/@angular/core/src/application_ref.d.ts(39,88): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/core/src/application_ref.d.ts(99,42): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/core/src/application_ref.d.ts(174,33): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/core/src/change_detection/differs/default_keyvalue_differ.d.ts(24,15): error TS2304: Cannot find name 'Map'.
node_modules/@angular/core/src/change_detection/differs/default_keyvalue_differ.d.ts(26,16): error TS2304: Cannot find name 'Map'.
node_modules/@angular/core/src/di/reflective_provider.d.ts(105,123): error TS2304: Cannot find name 'Map'.
node_modules/@angular/core/src/di/reflective_provider.d.ts(105,165): error TS2304: Cannot find name 'Map'.
node_modules/@angular/core/src/facade/async.d.ts(27,33): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/core/src/facade/async.d.ts(28,45): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/core/src/facade/collection.d.ts(1,25): error TS2304: Cannot find name 'MapConstructor'.
node_modules/@angular/core/src/facade/collection.d.ts(2,25): error TS2304: Cannot find name 'SetConstructor'.
node_modules/@angular/core/src/facade/collection.d.ts(4,27): error TS2304: Cannot find name 'Map'.
node_modules/@angular/core/src/facade/collection.d.ts(4,39): error TS2304: Cannot find name 'Map'.
node_modules/@angular/core/src/facade/collection.d.ts(7,9): error TS2304: Cannot find name 'Map'.
node_modules/@angular/core/src/facade/collection.d.ts(8,30): error TS2304: Cannot find name 'Map'.
node_modules/@angular/core/src/facade/collection.d.ts(11,43): error TS2304: Cannot find name 'Map'.
node_modules/@angular/core/src/facade/collection.d.ts(12,27): error TS2304: Cannot find name 'Map'.
node_modules/@angular/core/src/facade/collection.d.ts(14,23): error TS2304: Cannot find name 'Map'.
node_modules/@angular/core/src/facade/collection.d.ts(15,25): error TS2304: Cannot find name 'Map'.
node_modules/@angular/core/src/facade/collection.d.ts(100,41): error TS2304: Cannot find name 'Set'.
node_modules/@angular/core/src/facade/collection.d.ts(101,22): error TS2304: Cannot find name 'Set'.
node_modules/@angular/core/src/facade/collection.d.ts(102,25): error TS2304: Cannot find name 'Set'.
node_modules/@angular/core/src/facade/lang.d.ts(4,17): error TS2304: Cannot find name 'Map'.
node_modules/@angular/core/src/facade/lang.d.ts(5,17): error TS2304: Cannot find name 'Set'.
node_modules/@angular/core/src/facade/lang.d.ts(70,59): error TS2304: Cannot find name 'Map'.
node_modules/@angular/core/src/facade/promise.d.ts(2,14): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/core/src/facade/promise.d.ts(8,32): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/core/src/facade/promise.d.ts(9,38): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/core/src/facade/promise.d.ts(10,35): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/core/src/facade/promise.d.ts(10,93): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/core/src/facade/promise.d.ts(11,34): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/core/src/facade/promise.d.ts(11,50): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/core/src/facade/promise.d.ts(12,32): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/core/src/facade/promise.d.ts(12,149): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/core/src/facade/promise.d.ts(13,43): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/core/src/linker/component_resolver.d.ts(8,53): error TS2304: Cannot find name 'Promise'. node_modules/@angular/core/src/linker/component_resolver.d.ts(12,44): error TS2304: Cannot find name 'Promise'.

node_modules/@angular/core/src/linker/dynamic_component_loader.d.ts(62,148): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/core/src/linker/dynamic_component_loader.d.ts(103,144): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/core/src/linker/dynamic_component_loader.d.ts(108,139): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/core/src/linker/dynamic_component_loader.d.ts(109,135): error TS2304: Cannot find name 'Promise'.
node_modules/@angular/core/src/reflection/reflector.d.ts(28,22): error TS2304: Cannot find name 'Map'.
node_modules/@angular/core/src/reflection/reflector.d.ts(30,15): error TS2304: Cannot find name 'Map'.
node_modules/@angular/core/src/reflection/reflector.d.ts(32,15): error TS2304: Cannot find name 'Map'.
node_modules/@angular/core/src/reflection/reflector.d.ts(34,15): error TS2304: Cannot find name 'Map'.
node_modules/@angular/core/src/reflection/reflector.d.ts(36,16): error TS2304: Cannot find name 'Set'.
node_modules/@angular/core/src/testability/testability.d.ts(40,20): error TS2304: Cannot find name 'Map'.
node_modules/rxjs/Observable.d.ts(10,66): error TS2304: Cannot find name 'Promise'.
node_modules/rxjs/Observable.d.ts(66,60): error TS2304: Cannot find name 'Promise'.
node_modules/rxjs/Observable.d.ts(66,70): error TS2304: Cannot find name 'Promise'.
src/pushNotifications.service.ts(10,18): error TS4073: Parameter 'data' of public method from exported class has or is using private name 'PushNotification'.

npm ERR! Windows_NT 10.0.10586
npm ERR! argv "D:\NodeJS\node.exe" "D:\NodeJS\node_modules\npm\bin\npm-cli.js" "run" "build"
npm ERR! node v4.2.1
npm ERR! npm v3.9.5
npm ERR! code ELIFECYCLE
npm ERR! [email protected] build: tsc
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] build script 'tsc'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the angular2-notifications package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! tsc
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs angular2-notifications
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls angular2-notifications
npm ERR! There is likely additional logging output above.

Any clue what I am doing wrong?

NotificationsService should return the generated ID of a message

Hi,

first let me thank you for all your work! It works really nice.

I would like to create a sticky notification (when my app gets disconnected) that i remove later (when it gets reconnected).
The NotificationsService.remove(id:string) method does allow me to remove the notification. But it does neither allow me to specify the id of a notification (f.e. in the overrides) nor does it return the created id of the notification.

I see that i can subscribe to the onCreate event of the SimpleNotificationsComponent to receive the id of the created notification, but the SimpleNotificationsComponent is far away in my root component. It is the NotificationsService that i want to interact with. It would make its interface more consistent.

My suggestion would be

  1. Move the id generation code to the NotificationsService and return the generated id from .error(), .alert(),...
  2. Allow us to supply a custom id. How about an id attribute in the overrides?

Either of both suggestions would support my usecase.

Bernhard

preventLastDuplicates only checks active notifications

The description of the preventLastDuplicates flag says it prevents duplicates of the last notification shown, but it actually only prevents duplicate notifications if the last active notification is a duplicate. If the last notification is not active (user has dismissed or it has timed out) duplicate notifications are still shown.

RTL not working in the latest version

I added the following to the options:

rtl: true

but the icon appears on the left side of the notification and sometimes getting over the text. I remember this feature working in previous versions.

class "progress" in conflict with materializecss

Hi,
the class "progress" is in conflict with MaterializeCSS.

Css class for materializeCss :
position: relative; height: 4px; /* display: block; */ width: 100%; background-color: #acece6; border-radius: 2px; margin: 0.5rem 0 1rem 0; overflow: hidden;

the progress toaster is misaligned with toaster.
maybe you should change the classname of progress widget ?

Best regards

Notifications with custom Angular 2 exception handler

Hi, just looking for information/help.

I'm trying to use the notification service along with a custom exception handler class that extends Angular 2's ExceptionHandler.

@Injectable()
export class MyExceptionHandler extends ExceptionHandler {

    constructor(private logger : LoggerService, private notificationService : NotificationsService) {
        super(logger);
    }

    call(error, stackTrace = null, reason = null) {
        this.logger.error(error, "Logging the error");
        this.notificationService.error("Notify other components", ExceptionHandler.exceptionToString(error));
    }

}

MyExceptionHandler is provided on bootstrap so I provide the NotificationsService there also.

bootstrap(AppComponent, [
    // Other items...
    LoggerService, // Another custom class
    NotificationsService,
    {provide: ExceptionHandler, useClass: MyExceptionHandler}
]);

However, no notifications are shown when I try to raise an exception in AppComponent. My LoggerService (another custom class) is able to log the exception.

import { Component } from '@angular/core';
import { LoggerService }from './shared/services/logger/logger.service';
import {NotificationsService, SimpleNotificationsComponent} from "angular2-notifications";

@Component({
  selector: 'my-app',
  directives: [SimpleNotificationsComponent],
  template: `
              <h1>My First Angular 2 App</h1> 
              <button (click)="TestError()">Test Error</button>
              <simple-notifications></simple-notifications>
            `
})
export class AppComponent { 
  constructor(private logger : LoggerService, private notificationService : NotificationsService) {
  }
  TestError() {
    throw new Error("Test Error");
  }
}

Just to confirm everything is setup correctly, I can get notifications to show if I replace the line in TestError() with this:

this.notificationService.error("Error Title", "Error Content");

Am I missing something here or approaching this incorrectly?

use with webpack

Hello sir.

When I am injecting NotificationsService into my webpack project's service. I am getting this error message:

WARNING in ./~/angular2-notifications/lib/simpleNotifications.component.js
Cannot find source file '../src/simpleNotifications.component.ts': Error: Cannot resolve 'file' or 'directory' ../src/simpleNotifications.component.ts in /Users/zju/Codes/maestro-web-client/node_modules/angular2-notifications/lib

WARNING in ./~/angular2-notifications/lib/notifications.service.js
Cannot find source file '../src/notifications.service.ts': Error: Cannot resolve 'file' or 'directory' ../src/notifications.service.ts in /Users/zju/Codes/maestro-web-client/node_modules/angular2-notifications/lib

WARNING in ./~/angular2-notifications/lib/notification.component.js
Cannot find source file '../src/notification.component.ts': Error: Cannot resolve 'file' or 'directory' ../src/notification.component.ts in /Users/zju/Codes/maestro-web-client/node_modules/angular2-notifications/lib

WARNING in ./~/angular2-notifications/lib/max.pipe.js
Cannot find source file '../src/max.pipe.ts': Error: Cannot resolve 'file' or 'directory' ../src/max.pipe.ts in /Users/zju/Codes/maestro-web-client/node_modules/angular2-notifications/lib

WARNING in ./~/angular2-notifications/lib/icons.js
Cannot find source file '../src/icons.ts': Error: Cannot resolve 'file' or 'directory' ../src/icons.ts in /Users/zju/Codes/maestro-web-client/node_modules/angular2-notifications/lib

Any solutions?

Angular 2 notifications runtime error in Angular2-Rc.5 webpack using ng build --prod

The app works when on localhost:4200, but when using
ng build --prod
command to build the application to production mode, I get the following error at the runtime:

polyfills.c27b87b….bundle.js:1 Unhandled Promise rejection: Template parse errors:
Can't bind to 'item' since it isn't a known property of 'simple-notification'.
1. If 'simple-notification' is an Angular component and it has 'item' input, then verify that it is part of this module.
2. If 'simple-notification' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message.
 ("<simple-notification
                *ngFor="let a of notifications; let i = index"
                [ERROR ->][item]="a"
                [timeOut]="timeOut"
                [clickToClose]="clickToClose"
"): t@4:16
Can't bind to 'timeOut' since it isn't a known property of 'simple-notification'.
1. If 'simple-notification' is an Angular component and it has 'timeOut' input, then verify that it is part of this module.
2. If 'simple-notification' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message.
 ("          *ngFor="let a of notifications; let i = index"
                [item]="a"
                [ERROR ->][timeOut]="timeOut"
                [clickToClose]="clickToClose"
                [maxLength]="maxLen"): t@5:16
Can't bind to 'clickToClose' since it isn't a known property of 'simple-notification'.
1. If 'simple-notification' is an Angular component and it has 'clickToClose' input, then verify that it is part of this module.
2. If 'simple-notification' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message.
 ("
                [item]="a"
                [timeOut]="timeOut"
                [ERROR ->][clickToClose]="clickToClose"
                [maxLength]="maxLength"
                [showProgressBa"): t@6:16
Can't bind to 'maxLength' since it isn't a known property of 'simple-notification'.
1. If 'simple-notification' is an Angular component and it has 'maxLength' input, then verify that it is part of this module.
2. If 'simple-notification' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message.
 ("
                [timeOut]="timeOut"
                [clickToClose]="clickToClose"
                [ERROR ->][maxLength]="maxLength"
                [showProgressBar]="showProgressBar"
                [pauseOnH"): t@7:16
Can't bind to 'showProgressBar' since it isn't a known property of 'simple-notification'.
1. If 'simple-notification' is an Angular component and it has 'showProgressBar' input, then verify that it is part of this module.
2. If 'simple-notification' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message.
 ("              [clickToClose]="clickToClose"
                [maxLength]="maxLength"
                [ERROR ->][showProgressBar]="showProgressBar"
                [pauseOnHover]="pauseOnHover"
                [th"): t@8:16
Can't bind to 'pauseOnHover' since it isn't a known property of 'simple-notification'.
1. If 'simple-notification' is an Angular component and it has 'pauseOnHover' input, then verify that it is part of this module.
2. If 'simple-notification' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message.
 ("        [maxLength]="maxLength"
                [showProgressBar]="showProgressBar"
                [ERROR ->][pauseOnHover]="pauseOnHover"
                [theClass]="theClass"
                [rtl]="rtl"
"): t@9:16
Can't bind to 'theClass' since it isn't a known property of 'simple-notification'.
1. If 'simple-notification' is an Angular component and it has 'theClass' input, then verify that it is part of this module.
2. If 'simple-notification' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message.
 ("  [showProgressBar]="showProgressBar"
                [pauseOnHover]="pauseOnHover"
                [ERROR ->][theClass]="theClass"
                [rtl]="rtl"
                [animate]="animate"
"): t@10:16
Can't bind to 'rtl' since it isn't a known property of 'simple-notification'.
1. If 'simple-notification' is an Angular component and it has 'rtl' input, then verify that it is part of this module.
2. If 'simple-notification' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message.
 ("                [pauseOnHover]="pauseOnHover"
                [theClass]="theClass"
                [ERROR ->][rtl]="rtl"
                [animate]="animate"
                [position]="i"
"): t@11:16
Can't bind to 'animate' since it isn't a known property of 'simple-notification'.
1. If 'simple-notification' is an Angular component and it has 'animate' input, then verify that it is part of this module.
2. If 'simple-notification' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message.
 ("
                [theClass]="theClass"
                [rtl]="rtl"
                [ERROR ->][animate]="animate"
                [position]="i"
                [icons]="icons"
"): t@12:16
Can't bind to 'position' since it isn't a known property of 'simple-notification'.
1. If 'simple-notification' is an Angular component and it has 'position' input, then verify that it is part of this module.
2. If 'simple-notification' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message.
 ("
                [rtl]="rtl"
                [animate]="animate"
                [ERROR ->][position]="i"
                [icons]="icons"
                >
"): t@13:16
Can't bind to 'icons' since it isn't a known property of 'simple-notification'.
1. If 'simple-notification' is an Angular component and it has 'icons' input, then verify that it is part of this module.
2. If 'simple-notification' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message.
 ("
                [animate]="animate"
                [position]="i"
                [ERROR ->][icons]="icons"
                >
            </simple-notification>
"): t@14:16 ; Zone: <root> ; Task: Promise.then ; Value: e {message: "Template parse errors:↵Can't bind to 'item' since … >↵            </simple-notification>↵"): t@14:16", stack: "Error: Template parse errors:↵Can't bind to 'item'…/polyfills.c27b87b9e504b84ce8dc.bundle.js:2:4680)"}

Not sure if this error is from this package or from the angular 2 cli/webpack.

Notification don't work

Hello,

I'm trying to use the notification, but i'm with a problem.

When I call the method sucess in my event onclick the notification work very well, but when I call the method inside other method called from the method called from the event click, dont work.

If I force the change in page so it's works!

Plis, anyone could help me?

Thanks!

module do not works after build

then i use this module in local build its works fine but after build using sistemjs i got errors

lib-2f3a00f50a.js:7 Unhandled Promise rejection: Template parse errors:
Can't bind to 'item' since it isn't a known property of 'simple-notification'.
1. If 'simple-notification' is an Angular component and it has 'item' input, then verify that it is part of this module.
2. If 'simple-notification' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message.
 ("<simple-notification
                *ngFor="let a of notifications; let i = index"
                [ERROR ->][item]="a"
                [timeOut]="timeOut"
                [clickToClose]="clickToClose"
"): a@4:16
Can't bind to 'timeOut' since it isn't a known property of 'simple-notification'.
1. If 'simple-notification' is an Angular component and it has 'timeOut' input, then verify that it is part of this module.
2. If 'simple-notification' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message.
 ("          *ngFor="let a of notifications; let i = index"
                [item]="a"
                [ERROR ->][timeOut]="timeOut"
                [clickToClose]="clickToClose"
                [maxLength]="maxLen"): a@5:16

all configuration and setup is done as described in example.
Am I missing something or am I doing something wrong?

Not working with angular2.beta.14

I followed the steps provided , but I get a runtime error as soon as I include the NotificaitonsService
import {NotificationsService} from 'angular2-notifications/components';

simplenot

Do let me know what could the issue here

options

It appears that lastOnBottom and maxStacks are not working correctly, both properties are always set to the default irrespective of what I set them to.

Great library!

npmjs

Hello,

Can you update to the last version the npm package please? :) At least with this PR: #39

Thanks a lot.

Warnings : cannot find source files

The directive is working great! but i see these warnings -

WARNING in ./~/angular2-notifications/lib/notifications.service.js Cannot find source file '../src/notifications.service.ts': Error: Cannot resolve 'file' or 'directory' ../src/notifications.service.ts in /Users/sachin/myproject/node_modules/angular2-notifications/lib

WARNING in ./~/angular2-notifications/lib/simpleNotifications.component.js Cannot find source file '../src/simpleNotifications.component.ts': Error: Cannot resolve 'file' or 'directory' ../src/simpleNotifications.component.ts in /Users/sachin/myproject/node_modules/angular2-notifications/lib

and few more similar warnings...

I am using webpack and have imported the directive like this -
import {SimpleNotificationsComponent, NotificationsService} from 'angular2-notifications/components';

Thanks in advance!

notifications are not shown, with no errors!

Hi, first thanks for this plugin, I tried it and no notifications are shown here's a plunker with the error, when you click on the button nothing happen !!
Am I doing something wrong here?
Is there a step missing I need to do to get it to work?
Also the NotificationsService should by provided in the main.ts file or the app.component.ts file, otherwise an error will occur, this step is missing from the docs.

Unable to import with SystemJS

Hi,

Sorry to bother you with that but I am unable to use SystemJS to import your plugin.

I have added to the map object of systemJs :

'notifications': 'node_modules/angular2-notifications'

And to the packages object :

'notifications': { main: 'components.js', defaultExtension: 'js' }

Then in my component ts file, I just do :

import { SimpleNotificationsComponent } from 'notifications'

However, when I run tsc, I always have this error : app/components/core/app/app.component.ts(4,46): error TS2307: Cannot find module 'notifications

Am I doing something wrong ?

Thanks in advance

Regards

Document reuse

I can't seem to get notifications working unless the directive is included in the template of the component that does the notification. What I'd like to do is have the directive in my main/app component and only inject the service into the individual components that produce the notifications, therefore reusing the same "toaster". Is it possible?

NotificationsService only available on children, not throug router-outlet

Other services are working properly. I don't know if this may be a RC4 feature/bug or something related to implementation. I could perfectly declare it in every routed component, however I don't think this is the way the package was intended to be used.

What I do, even if declaring a service globally is discouraged by the official documentation) is:

Declare the componen and inject service on your main Component

import {NotificationsService, SimpleNotificationsComponent} from "angular2-notifications";

@Component({
    ...
    providers: [NotificationsService],
    directives: [SimpleNotificationsComponent, ...]
    template: `
            <child-component></child-component>
            <router-outlet></router-outlet>
    `,
    ...
})
export class AppComponent{
    public options = {
        timeOut: 2000,
        showProgressBar: false
    };
}

bootstrap(AppComponent, [APP_ROUTER_PROVIDERS, NotificationsService]);

Use everywhere

It works properly with the actual Component where the SimpleNotificationsComponent was used, and it's children.

import {NotificationsService} from "angular2-notifications";

/**
  * This is a child component
  */
@Component({
    ...
    selector: 'child-componet',
    providers: [NotificationsService],
    ...
export class ChildComponent(){
    constructor(private ns:NotificationsService){}
    someFunction(){
        this.ns.info('title','content');
    }
}

However it doesn't work for routed components

import {NotificationsService} from "angular2-notifications";

/**
  * This is a routed component
  */
@Component({
    ...
    providers: [NotificationsService],
    ...
export class RoutedComponent(){
    constructor(private ns:NotificationsService){}
    someFunction(){
        this.ns.info('title','content');
    }
}

No Directive annotation found on SimpleNotificationsComponent

I'm using webpack. In my main application component I do the following:

import {SimpleNotificationsComponent} from 'angular2-notifications/components';
...
@Component({
  selector: 'body',
  providers: [ FORM_PROVIDERS ],
  directives: [Sidebar, Navbar, ROUTER_DIRECTIVES, SimpleNotificationsComponent],
  styles: [require('../../scss/application.scss')],
  encapsulation: ViewEncapsulation.None,
  template: require('./core.html')
})

And then in browser console I see the error: EXCEPTION: No Directive annotation found on SimpleNotificationsComponent

I don't have any ideas of how to fix it..

angular2 cli with notifiction

Hi Flauc,
Could you please advise me on, how to use notification in angular2 cli (rc4)..I am new to angular2..Please give me your guidance step by step that i can easily under stand..

Thanks and Regards
Venkatesh

Test angular2 Notifications

Hi every,
I just a request I want to test my Angular2 App with Karma. But when I tried to include angular2 notification into Karma it's return.
exports is not defined

Because I think module and file component.js don't support CommonJS, require and export.

You have schedule to testing angular2 Notification or not at all?

Thanks for answer

Configure notification position

👏🏾 Great component!

Just wander is there a way to set notification's popup position, let's say set them to top right?

Fix TypeScript typing

After renaming NotificationsService::removeAll() to NotificationsService::remove() typings should be updated accordingly in angular2-notifications/notifications.service.d.ts.

Btw how do you publish this project to npm? I don't see prepublish scripts in package.json

Override default style

Hi @flauc,

Is there a way to override the default style ?

For example, I want to change the z-index of the simple-notification-wrapper div because it displays behind the black opacity overlay of bootstrap modal.

Thanks

Module not found

hi there,

i am finding problems at use it wit webpack

ERROR in multi vendor Module not found: Error: Cannot resolve module 'angular2-notifications' in C:\Us ers\Sergio_2\auth-angular2-app @ multi vendor

here is the webpack config fragment
entry: { 'vendor': [ // Polyfills 'es6-shim', 'es6-promise', 'reflect-metadata', 'zone.js/dist/zone-microtask', 'zone.js/dist/long-stack-trace-zone', // Angular2 'angular2/platform/browser', 'angular2/platform/common_dom', 'angular2/core', 'angular2/router', 'angular2/http', // RxJS 'rxjs', // Other 'angular2-jwt', 'angular2-notifications' ], 'app': [ './src/index' ] }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.