|
| 1 | +# Pub/Sub Service for Angular 2 |
| 2 | + |
| 3 | +A simple publisher/subscriber service. |
| 4 | + |
| 5 | +## Usage |
| 6 | + - Import service in your codes. |
| 7 | + |
| 8 | + - Add service to App Module providers. |
| 9 | +```typescript |
| 10 | +... |
| 11 | + |
| 12 | +import { EventDispatcherService } from './path/to/service/angular2-pubsub.service'; // <= HERE |
| 13 | + |
| 14 | +@NgModule({ |
| 15 | +declarations: [ |
| 16 | + RootComponent, |
| 17 | + NavigationComponent, |
| 18 | + OverlayComponent |
| 19 | +], |
| 20 | +imports: [ |
| 21 | + BrowserModule, |
| 22 | + FormsModule, |
| 23 | + HttpModule |
| 24 | +], |
| 25 | +providers: [EventDispatcherService], // <= AND HERE |
| 26 | +bootstrap: [RootComponent] |
| 27 | +}) |
| 28 | + |
| 29 | +... |
| 30 | +``` |
| 31 | + - And import service wherever you want |
| 32 | + |
| 33 | +## Documentation |
| 34 | + |
| 35 | +#### Class Overview |
| 36 | + |
| 37 | +```typescript |
| 38 | +declare class PubSubService{ |
| 39 | + private events: Object; |
| 40 | + $pub(event: string, eventObject?: any): void; |
| 41 | + $sub(event: string): <Observable<number>>; |
| 42 | +} |
| 43 | +``` |
| 44 | + |
| 45 | +#### PubSubService.$pub(event: stirng, eventObject?: any): void |
| 46 | + |
| 47 | +Publish event to all subscriber. |
| 48 | + |
| 49 | +etc. |
| 50 | +```typescript |
| 51 | +export class OverlayComponent implements OnInit, OnDestroy { |
| 52 | + constructor(private pubsub: PubSubService) { } |
| 53 | + |
| 54 | + anyFunc(){ |
| 55 | + this.pubsub.$pub('pleaseCloseSidenav', 'helloIAmOverlay'); |
| 56 | + } |
| 57 | +} |
| 58 | +``` |
| 59 | + |
| 60 | +#### PubSubService.$sub(event: stirng): <Observable<number>> |
| 61 | + |
| 62 | +Subscribe to channel. |
| 63 | + |
| 64 | +etc. |
| 65 | +```typescript |
| 66 | +export class NavigationComponent implements OnInit, OnDestroy { |
| 67 | + sideanvSub: any; |
| 68 | + |
| 69 | + constructor(private pubsub: EventDispatcherService) { } |
| 70 | + |
| 71 | + ngOnInit() { |
| 72 | + this.closeSidenavSub = this.pubsub.$sub('pleaseCloseSidenav').subscribe((from) => { |
| 73 | + from ? this.sidenavOpened = false : void 0 |
| 74 | + }); |
| 75 | + } |
| 76 | + ngOnDestroy() { |
| 77 | + this.closeSidenavSub.unsubscribe(); |
| 78 | + } |
| 79 | +``` |
| 80 | +
|
| 81 | + $sub method have one bug. RxJS Subscriber call subscribe method on start like Angular 1.x $scope.$watch. |
| 82 | + |
| 83 | +```typescript |
| 84 | +this.closeSidenavSub = this.pubsub.$sub('pleaseCloseSidenav').subscribe((from) => { |
| 85 | + console.log(form); |
| 86 | +}); |
| 87 | + |
| 88 | +// => 0 |
| 89 | +``` |
0 commit comments