<!DOCTYPE html>
<html>
  <head>
    <title>Angular2 Simple MQ Service Example</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- 1. Load libraries -->
     <!-- Polyfill(s) for older browsers -->
    <script src="https://unpkg.com/core-js/client/shim.min.js"></script>
    <script src="https://unpkg.com/zone.js@0.7.4?main=browser"></script>
    <script src="https://unpkg.com/systemjs@0.19.40/dist/system.src.js"></script>

    <!-- 2. Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
  </head>

  <!-- 3. Display the application -->
  <body>
    <app-component>Angular2 Simple MQ Service Example ...</app-component>
  </body>
</html>
import {Component} from '@angular/core';
import {SimpleMQ} from 'ng2-simple-mq';


@Component({
	'selector': 'app-component',
	'template': `
  	<p>
  	ng2-simple-mq is available in
    	<a href="https://www.npmjs.com/package/ng2-simple-mq">npm</a> and 
      <a href="https://github.com/J-Siu/ng2-simple-mq">github</a>.
    This example is available in 
      <a href="https://github.com/J-Siu/ng2-simple-mq-example">github</a>.
    </p>
		<div style="border: 1px solid;margin:5px;padding:5px">
	  <h3>{{title}}</h3>
		<div>Send message to component one <input [(ngModel)]="msgOne"><button (click)="sendToOne()">Send</button></div>
		<div>Send message to component two <input [(ngModel)]="msgTwo"><button (click)="sendToTwo()">Send</button></div>
		<div>Broadcast message <input [(ngModel)]="msgBroadcast"><button (click)="broadcast()">Broadcast</button></div>
		<one-component [parent]="myId"></one-component>
		<two-component [parent]="myId"></two-component>
    </div>
		`
})
export class AppComponent {
	title = 'Angular2 Simple Component MQ Example';
	msgOne: string;
	msgTwo: string;
	msgBroadcast: string;

	myId = 'parent';

	constructor(private smq: SimpleMQ) { }

	sendToOne() {
		// Publish to queue name 'one'
		this.smq.publish('one', this.msgOne);
	}
	sendToTwo() {
		// Publish to queue name 'two'
		this.smq.publish('two', this.msgTwo);
	}
	broadcast() {
		// Publish to queue name 'broadcast'
		this.smq.publish(this.myId, this.msgBroadcast);
	}
}
(function(global) {
  System.config({
    // DEMO ONLY! REAL CODE SHOULD NOT TRANSPILE IN THE BROWSER
    transpiler: 'typescript',
    typescriptOptions: {
      emitDecoratorMetadata: true
    },
    paths: {
      // paths serve as alias
      'npm:': 'https://unpkg.com/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',

      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
      '@angular/upgrade': 'npm:@angular/upgrade/bundles/upgrade.umd.js',

      // other libraries
      'rxjs': 'npm:rxjs',
      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api',
      'ts': 'npm:plugin-typescript@4.0.10/lib/plugin.js',
      'typescript': 'npm:typescript@2.0.2/lib/typescript.js',

      'angular2-uuid': 'https://unpkg.com/angular2-uuid/index.js',
      'ng2-simple-mq': 'https://npmcdn.com/ng2-simple-mq/lib/simple-mq.js'

    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      '.': {
        defaultExtension: 'ts'
      },
      app: {
        main: './main.ts',
        defaultExtension: 'ts'
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });
})(this);
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { SimpleMQ } from 'ng2-simple-mq';

import { AppComponent } from './app.component';

import {OneComponent} from './one.component';
import {TwoComponent} from './two.component';

@NgModule({
	imports: [
		BrowserModule,
		FormsModule
	],
	declarations: [
		AppComponent,
		OneComponent,
		TwoComponent
	],
	providers: [
		SimpleMQ
	],
	bootstrap: [
		AppComponent
	]
})
export class AppModule { }


platformBrowserDynamic().bootstrapModule(AppModule);
# ng2-simple-mq

A simple message queue for Angular 2 inter-component communication base on RxJS.

Name/ID(string) base API. RxJS object not exposed.

(This pacakge does not communicate with RabbitMQ or any other message queue software/service.)

## Index

- [Install](#install)
- [Usage](#usage)
	- ["noImplicitAny": false](#noimplicitany-false)
	- [Import into Angular 2 application (typescript)](#import-into-angular-2-application-typescript)
	- [API](#api)
		- [newQueue(name: string): boolean](#newqueuename-string-boolean)
		- [delQueue(name: string): boolean](#delqueuename-string-boolean)
		- [getQueue(): string[]](#getqueue-string)
		- [getSubscription(): string[]](#getsubscription-string)
		- [publish(name: string, msg: any, lazy = true): boolean](#publishname-string-msg-any-lazy--true-boolean)
		- [subscribe(name: string, callback: (any) => void, lazy = true): string](#subscribename-string-callback-any--void-lazy--true-string)
		- [unsubscribe(id: string): boolean](#unsubscribeid-string-boolean)
- [Example](#example)
- [Contributors](#contributors)
- [Changelog](#changelog)
- [License](#license)

## Install

```
npm install ng2-simple-mq
```

## Usage

### "noImplicitAny": false

Must set `"noImplicitAny": false` in application __tsconfig.json__. Else following error may occure at build time:

    error TS7006: Parameter 'any' implicitly has an 'any' type

### Import into Angular 2 application (typescript)

`ng2-simple-mq` is implemented as Angular 2 injectable service name __SimpleMQ__.

__For module using SimpleMQ__

Add `SimpleMQ` into module providers (eg. [app.module.ts](https://github.com/J-Siu/ng2-simple-mq-example/blob/master/app/app.module.ts)).

```javascript
import { SimpleMQ } from 'ng2-simple-mq';

@NgModule({
	providers: [SimpleMQ]
})
```

__For each child component using SimpleMQ__

```javascript
import { SimpleMQ } from 'ng2-simple-mq';

export class ChildComponent {

	constructor(private smq: SimpleMQ) { }

}
```

### API

##### newQueue(name: string): boolean

`newQueue` will create queue `name`.

Return `false` if queue `name` exist.

```javascript
this.smq.newQueue('broadcast');
```

##### delQueue(name: string): boolean

`delQueue` will delete queue `name`.

Return `false` if queue `name` does not exist.

```javascript
this.smq.delQueue('broadcast');
```

##### getQueue(): string[]

`getQueue` will return all queue name in string array.
```javascript
let q: string[] = this.smq.getQueue();
```

##### getSubscription(): string[]

`getSubscription` will return all subscription id in string array.
```javascript
let ids: string[] = this.st.getSubscription();
```

##### publish(name: string, msg: any, lazy = true): boolean

`publish` will put `msg` into queue `name`.

If `lazy = true`(default), queue `name` will be created automatically if not exist yet.

Return true if successful.

Return false if any of following is true:
- `lazy = false`, and queue `name` does not exist.
- `name` is undefined.
- `msg` is undefined.

```javascript
// lazy mode
message = 'This is a broadcast message';
this.smq.publish('broadcast',message);
```

##### subscribe(name: string, callback: (any) => void, lazy = true): string

`subscribe` will link `callback` function to queue `name`. Whenever queue `name` receive a new message, `callback` will be invoked.

If `lazy = true`(default), queue `name` will be created automatically if not exist yet.

Return subscription id if successful.

Return empty string if any of following is true:
- `lazy = false`, and queue `name` does not exist.
- `name` is undefined.
- `callback` is undefined.

Either use Lambda(fat arrow) in typescript to pass in callback or bind `this` to another variable in javascript, else `this` scope will be lost.

__Lambda(fat arrow)__
```javascript
broadcastMsg;

ngOnInit() {
	// lazy mode
	this.smq.subscribe('broadcast', e => this.receiveBroadcast(e));
}

receiveBroadcast(m) {
	this.broadcastMsg = m;
}
```

##### unsubscribe(id: string): boolean

`unsubscribe` will cancel subscription using `id`.

`unsubscribe` will return false if `id` is undefined or `id` is not found in subscription list.

```javascript
id: string;

this.st.unsubscribe(this.id);
```

## Example

Github: [ng2-simple-mq-example](https://github.com/J-Siu/ng2-simple-mq-example)
Plunker: [Angular2 Simple MQ Example](http://embed.plnkr.co/e8Crbf/)

## Contributors

* [John Sing Dao Siu](https://github.com/J-Siu)

## Changelog

* 0.1.0-alpha - Initial
* 0.1.1-alpha - Add Readme.md
* 0.1.2-alpha - Readme.md fix
* 0.1.3-alpha - Fix components.js
* 0.2.0
	- Complete Readme.md
	- Fix index.js and index.d.ts
* 0.2.1
	- API change
		- newQueue return boolean
	- API new
		- delQueue
		- getSubscription
		- unsubscribe
* 0.2.2
	- Support Angular2 RC5
* 0.2.3
	- Fix Readme.md
* 1.2.4
	- Support Angular2 ^2.0.0
	- Clean up package
* 1.2.5
	- Add Plunker example
* 1.2.6
	- Support Angular2 ^2.4.1
	- Replace node-uuid with angular2-uuid
	- Add instruction for `"noImplicitAny": false`

## License

The MIT License

Copyright (c) 2017

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import {Component, OnInit, Input} from '@angular/core';
import {SimpleMQ} from 'ng2-simple-mq';

@Component({
	'selector': 'one-component',
	'template': `
  	<div style="border: 1px solid;margin:5px;padding:5px">
		<h3>{{title}}</h3>
		<div>Send message to component two <input [(ngModel)]="msgTwo"><button (click)="sendToTwo()">Send</button></div>
		<div>Broadcast message <input [(ngModel)]="msgBroadcast"><button (click)="broadcast()">Broadcast</button></div>
		<div>Receive from queue 'one' : {{msg}}</div>
		<div>Receive from queue 'broadcast' : {{broadcastMsg}}</div>
		</div>`
})
export class OneComponent implements OnInit {
	title = 'Component One';
	msg;
	msgTwo;
	msgBroadcast;
	broadcastMsg;

	@Input() parent;

	constructor(private smq: SimpleMQ) { }
	ngOnInit() {
		this.smq.subscribe('one', e => this.receiveMsg(e));
		this.smq.subscribe(this.parent, e => this.receiveBroadcast(e));
	}
	sendToTwo() {
		// Publish to queue name 'two'
		this.smq.publish('two', this.msgTwo);
	}
	broadcast() {
		// Publish to queue name 'broadcast'
		this.smq.publish(this.parent, this.msgBroadcast);
	}
	receiveMsg(m) {
		this.msg = m;
		console.log('1:' + this.msg);
	}
	receiveBroadcast(m) {
		this.broadcastMsg = m;
		console.log('1bc:' + this.broadcastMsg);
	}
}
import {Component, OnInit, Input} from '@angular/core';
import {SimpleMQ} from 'ng2-simple-mq';

@Component({
	'selector': 'two-component',
	'template': `
  	<div style="border: 1px solid;margin:5px;padding:5px">
		<h3>{{title}}</h3>
		<div>Send message to component one <input [(ngModel)]="msgOne"><button (click)="sendToOne()">Send</button></div>
		<div>Broadcast message <input [(ngModel)]="msgBroadcast"><button (click)="broadcast()">Broadcast</button></div>
		<div>Receive from queue 'two' : {{msg}}</div>
		<div>Receive from queue 'broadcast' : {{broadcastMsg}}</div>
		</div>`
})
export class TwoComponent implements OnInit {
	title = 'Component Two';
	msg;
	msgOne;
	msgBroadcast;
	broadcastMsg;

	@Input() parent;

	constructor(private smq: SimpleMQ) { }
	ngOnInit() {
		this.smq.subscribe('two', e => this.receiveMsg(e));
		this.smq.subscribe(this.parent, e => this.receiveBroadcast(e));
	}
	sendToOne() {
		// Publish to queue name 'one'
		this.smq.publish('one', this.msgOne);
	}
	broadcast() {
		// Publish to queue name 'broadcast'
		this.smq.publish(this.parent, this.msgBroadcast);
	}
	receiveMsg(m) {
		console.log('2:' + m);
		this.msg = m;
	}
	receiveBroadcast(m) {
		console.log('2bc:' + m);
		this.broadcastMsg = m;
	}
}