├── .editorconfig ├── .gitignore ├── LICENSE ├── README.md ├── angular.json ├── e2e ├── protractor.conf.js ├── src │ ├── app.e2e-spec.ts │ └── app.po.ts └── tsconfig.e2e.json ├── package.json ├── server └── index.js ├── src ├── app │ ├── app.component.css │ ├── app.component.html │ ├── app.component.spec.ts │ ├── app.component.ts │ ├── app.module.ts │ ├── websocket.events.ts │ └── websocket │ │ ├── index.ts │ │ ├── websocket.config.ts │ │ ├── websocket.interfaces.ts │ │ ├── websocket.module.spec.ts │ │ ├── websocket.module.ts │ │ ├── websocket.service.spec.ts │ │ └── websocket.service.ts ├── assets │ └── .gitkeep ├── browserslist ├── environments │ ├── environment.prod.ts │ └── environment.ts ├── favicon.ico ├── index.html ├── karma.conf.js ├── main.ts ├── polyfills.ts ├── styles.css ├── test.ts ├── tsconfig.app.json ├── tsconfig.spec.json └── tslint.json ├── tsconfig.json └── tslint.json /.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see http://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 4 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.md] 12 | max_line_length = off 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # compiled output 4 | /dist 5 | /tmp 6 | /out-tsc 7 | 8 | # dependencies 9 | /node_modules 10 | 11 | # IDEs and editors 12 | /.idea 13 | .project 14 | .classpath 15 | .c9/ 16 | *.launch 17 | .settings/ 18 | *.sublime-workspace 19 | 20 | # IDE - VSCode 21 | .vscode/* 22 | !.vscode/settings.json 23 | !.vscode/tasks.json 24 | !.vscode/launch.json 25 | !.vscode/extensions.json 26 | 27 | # misc 28 | /.sass-cache 29 | /connect.lock 30 | /coverage 31 | /libpeerconnection.log 32 | npm-debug.log 33 | yarn-error.log 34 | testem.log 35 | /typings 36 | 37 | # System Files 38 | .DS_Store 39 | Thumbs.db 40 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 AlexDaSoul 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Angular WebSocket starter 2 | 3 | > Angular service for WebSocket. Used Rx WebSocketSubject 4 | 5 | ## Installation 6 | For angular 6: 7 | ```bash 8 | $ git clone https://github.com/AlexDaSoul/angular-websocket-starter.git 9 | $ cd angular-websocket-starter 10 | $ npm install 11 | $ npm run start 12 | $ npm run server 13 | ``` 14 | 15 | ## Example 16 | 17 | #### Add WebSockets on your project 18 | 19 | > in app module 20 | 21 | Config: 22 | - url: string (server websocket url) 23 | - reconnectInterval: number (pause between connections) 24 | - reconnectAttempts: number (number of connection attempts) 25 | 26 | ```typescript 27 | import { BrowserModule } from '@angular/platform-browser'; 28 | import { NgModule } from '@angular/core'; 29 | 30 | import { AppComponent } from './app.component'; 31 | import { WebsocketModule } from './websocket'; 32 | 33 | 34 | @NgModule({ 35 | declarations: [ 36 | AppComponent 37 | ], 38 | imports: [ 39 | WebsocketModule.config({ 40 | url: 'http:localhost:8080' 41 | }) 42 | ], 43 | providers: [], 44 | bootstrap: [AppComponent] 45 | }) 46 | export class AppModule { 47 | } 48 | ``` 49 | 50 | 51 | > in components 52 | 53 | ```typescript 54 | import { Component, OnInit } from '@angular/core'; 55 | import { Observable } from 'rxjs'; 56 | 57 | import { WebsocketService } from './websocket'; 58 | import { WS } from './websocket.events'; 59 | 60 | export interface IMessage { 61 | id: number; 62 | text: string; 63 | } 64 | 65 | 66 | @Component({ 67 | selector: 'app-root', 68 | templateUrl: './app.component.html', 69 | styleUrls: ['./app.component.css'] 70 | }) 71 | export class AppComponent implements OnInit { 72 | 73 | private messages$: Observable; 74 | 75 | constructor(private wsService: WebsocketService) { 76 | } 77 | 78 | ngOnInit() { 79 | // get messages 80 | this.messages$ = this.wsService.on(WS.ON.MESSAGES); 81 | } 82 | 83 | public sendMessge(): void { 84 | this.wsService.send(WS.SEND.SEND_TEXT, 'My Message Text'); 85 | } 86 | 87 | } 88 | ``` 89 | 90 | 91 | > config for message names 92 | 93 | Open src/app/websocket.events.ts and edit names 94 | 95 | ```typescript 96 | export const WS = { 97 | ON: { 98 | MESSAGES: 'messages', 99 | COUNTER: 'counter', 100 | UPDATE_TEXTS: 'update-texts' 101 | }, 102 | SEND: { 103 | SEND_TEXT: 'set-text', 104 | REMOVE_TEXT: 'remove-text' 105 | } 106 | }; 107 | ``` 108 | -------------------------------------------------------------------------------- /angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "angular-websocket-starter": { 7 | "root": "", 8 | "sourceRoot": "src", 9 | "projectType": "application", 10 | "prefix": "app", 11 | "schematics": {}, 12 | "architect": { 13 | "build": { 14 | "builder": "@angular-devkit/build-angular:browser", 15 | "options": { 16 | "outputPath": "dist/angular-websocket-starter", 17 | "index": "src/index.html", 18 | "main": "src/main.ts", 19 | "polyfills": "src/polyfills.ts", 20 | "tsConfig": "src/tsconfig.app.json", 21 | "assets": [ 22 | "src/favicon.ico", 23 | "src/assets" 24 | ], 25 | "styles": [ 26 | "src/styles.css" 27 | ], 28 | "scripts": [] 29 | }, 30 | "configurations": { 31 | "production": { 32 | "fileReplacements": [ 33 | { 34 | "replace": "src/environments/environment.ts", 35 | "with": "src/environments/environment.prod.ts" 36 | } 37 | ], 38 | "optimization": true, 39 | "outputHashing": "all", 40 | "sourceMap": false, 41 | "extractCss": true, 42 | "namedChunks": false, 43 | "aot": true, 44 | "extractLicenses": true, 45 | "vendorChunk": false, 46 | "buildOptimizer": true 47 | } 48 | } 49 | }, 50 | "serve": { 51 | "builder": "@angular-devkit/build-angular:dev-server", 52 | "options": { 53 | "browserTarget": "angular-websocket-starter:build" 54 | }, 55 | "configurations": { 56 | "production": { 57 | "browserTarget": "angular-websocket-starter:build:production" 58 | } 59 | } 60 | }, 61 | "extract-i18n": { 62 | "builder": "@angular-devkit/build-angular:extract-i18n", 63 | "options": { 64 | "browserTarget": "angular-websocket-starter:build" 65 | } 66 | }, 67 | "test": { 68 | "builder": "@angular-devkit/build-angular:karma", 69 | "options": { 70 | "main": "src/test.ts", 71 | "polyfills": "src/polyfills.ts", 72 | "tsConfig": "src/tsconfig.spec.json", 73 | "karmaConfig": "src/karma.conf.js", 74 | "styles": [ 75 | "src/styles.css" 76 | ], 77 | "scripts": [], 78 | "assets": [ 79 | "src/favicon.ico", 80 | "src/assets" 81 | ] 82 | } 83 | }, 84 | "lint": { 85 | "builder": "@angular-devkit/build-angular:tslint", 86 | "options": { 87 | "tsConfig": [ 88 | "src/tsconfig.app.json", 89 | "src/tsconfig.spec.json" 90 | ], 91 | "exclude": [ 92 | "**/node_modules/**" 93 | ] 94 | } 95 | } 96 | } 97 | }, 98 | "angular-websocket-starter-e2e": { 99 | "root": "e2e/", 100 | "projectType": "application", 101 | "architect": { 102 | "e2e": { 103 | "builder": "@angular-devkit/build-angular:protractor", 104 | "options": { 105 | "protractorConfig": "e2e/protractor.conf.js", 106 | "devServerTarget": "angular-websocket-starter:serve" 107 | }, 108 | "configurations": { 109 | "production": { 110 | "devServerTarget": "angular-websocket-starter:serve:production" 111 | } 112 | } 113 | }, 114 | "lint": { 115 | "builder": "@angular-devkit/build-angular:tslint", 116 | "options": { 117 | "tsConfig": "e2e/tsconfig.e2e.json", 118 | "exclude": [ 119 | "**/node_modules/**" 120 | ] 121 | } 122 | } 123 | } 124 | } 125 | }, 126 | "defaultProject": "angular-websocket-starter" 127 | } -------------------------------------------------------------------------------- /e2e/protractor.conf.js: -------------------------------------------------------------------------------- 1 | // Protractor configuration file, see link for more information 2 | // https://github.com/angular/protractor/blob/master/lib/config.ts 3 | 4 | const { SpecReporter } = require('jasmine-spec-reporter'); 5 | 6 | exports.config = { 7 | allScriptsTimeout: 11000, 8 | specs: [ 9 | './src/**/*.e2e-spec.ts' 10 | ], 11 | capabilities: { 12 | 'browserName': 'chrome' 13 | }, 14 | directConnect: true, 15 | baseUrl: 'http://localhost:4200/', 16 | framework: 'jasmine', 17 | jasmineNodeOpts: { 18 | showColors: true, 19 | defaultTimeoutInterval: 30000, 20 | print: function() {} 21 | }, 22 | onPrepare() { 23 | require('ts-node').register({ 24 | project: require('path').join(__dirname, './tsconfig.e2e.json') 25 | }); 26 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); 27 | } 28 | }; -------------------------------------------------------------------------------- /e2e/src/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { AppPage } from './app.po'; 2 | 3 | describe('workspace-project App', () => { 4 | let page: AppPage; 5 | 6 | beforeEach(() => { 7 | page = new AppPage(); 8 | }); 9 | 10 | it('should display welcome message', () => { 11 | page.navigateTo(); 12 | expect(page.getParagraphText()).toEqual('Welcome to angular-websocket-starter!'); 13 | }); 14 | }); 15 | -------------------------------------------------------------------------------- /e2e/src/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, by, element } from 'protractor'; 2 | 3 | export class AppPage { 4 | navigateTo() { 5 | return browser.get('/'); 6 | } 7 | 8 | getParagraphText() { 9 | return element(by.css('app-root h1')).getText(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /e2e/tsconfig.e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "module": "commonjs", 6 | "target": "es5", 7 | "types": [ 8 | "jasmine", 9 | "jasminewd2", 10 | "node" 11 | ] 12 | } 13 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "angular-websocket-starter", 3 | "description": "Angular service for WebSocket", 4 | "autor": "Alex Duchnovsky", 5 | "license": "MIT", 6 | "version": "0.0.0", 7 | "repository": { 8 | "type": "git", 9 | "url": "git+https://github.com/AlexDaSoul/angular-websocket-starter.git" 10 | }, 11 | "bugs": { 12 | "url": "https://github.com/AlexDaSoul/angular-websocket-starter/issues" 13 | }, 14 | "scripts": { 15 | "ng": "ng", 16 | "start": "ng serve", 17 | "build": "ng build", 18 | "test": "ng test", 19 | "lint": "ng lint", 20 | "e2e": "ng e2e", 21 | "server": "node server" 22 | }, 23 | "private": true, 24 | "dependencies": { 25 | "@angular/animations": "^6.0.3", 26 | "@angular/common": "^6.0.3", 27 | "@angular/compiler": "^6.0.3", 28 | "@angular/core": "^6.0.3", 29 | "@angular/forms": "^6.0.3", 30 | "@angular/http": "^6.0.3", 31 | "@angular/platform-browser": "^6.0.3", 32 | "@angular/platform-browser-dynamic": "^6.0.3", 33 | "@angular/router": "^6.0.3", 34 | "core-js": "^2.5.4", 35 | "rxjs": "^6.0.0", 36 | "ws": "^5.2.1", 37 | "zone.js": "^0.8.26" 38 | }, 39 | "devDependencies": { 40 | "@angular-devkit/build-angular": "~0.6.8", 41 | "@angular/cli": "~6.0.8", 42 | "@angular/compiler-cli": "^6.0.3", 43 | "@angular/language-service": "^6.0.3", 44 | "@types/express": "^4.16.0", 45 | "@types/jasmine": "~2.8.6", 46 | "@types/jasminewd2": "~2.0.3", 47 | "@types/node": "~8.9.4", 48 | "@types/websocket": "0.0.39", 49 | "codelyzer": "~4.2.1", 50 | "jasmine-core": "~2.99.1", 51 | "jasmine-spec-reporter": "~4.2.1", 52 | "karma": "~1.7.1", 53 | "karma-chrome-launcher": "~2.2.0", 54 | "karma-coverage-istanbul-reporter": "~2.0.0", 55 | "karma-jasmine": "~1.1.1", 56 | "karma-jasmine-html-reporter": "^0.2.2", 57 | "protractor": "~5.3.0", 58 | "ts-node": "~5.0.1", 59 | "tslint": "~5.9.1", 60 | "typescript": "~2.7.2" 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /server/index.js: -------------------------------------------------------------------------------- 1 | const WebSocketServer = require('ws').Server; 2 | const wss = new WebSocketServer({ port: 6759 }); 3 | 4 | const messages = [ 5 | { 6 | id: 1, 7 | text: 'Hello everyone!!!' 8 | }, 9 | { 10 | id: 2, 11 | text: 'I\'m here!!!' 12 | }, 13 | { 14 | id: 3, 15 | text: 'Who there???' 16 | }, 17 | { 18 | id: 4, 19 | text: 'Damn!' 20 | }, 21 | { 22 | id: 5, 23 | text: 'I\'m off' 24 | } 25 | ]; 26 | const texts = ['Text Data']; 27 | let counter = 0; 28 | 29 | 30 | wss.on('connection', (ws) => { 31 | console.log('WebSocket connection!'); 32 | 33 | ws.on('message', (event) => { 34 | const data = JSON.parse(event); 35 | const res = JSON.parse(data); 36 | 37 | switch (res.event) { 38 | case 'set-text': 39 | texts.unshift(res.data); 40 | 41 | break; 42 | case 'remove-text': 43 | texts.splice(res.data, 1); 44 | break; 45 | } 46 | 47 | ws.send(JSON.stringify({ 48 | event: 'update-texts', 49 | data: texts 50 | })); 51 | 52 | console.log('message', data); 53 | }); 54 | 55 | ws.send(JSON.stringify({ 56 | event: 'messages', 57 | data: messages 58 | })); 59 | 60 | ws.send(JSON.stringify({ 61 | event: 'update-texts', 62 | data: texts 63 | })); 64 | 65 | const timer = () => { 66 | ws.send(JSON.stringify({ 67 | event: 'counter', 68 | data: ++counter 69 | })); 70 | }; 71 | 72 | const interval = setInterval(timer, 1000); 73 | 74 | ws.on('close', () => { 75 | console.log('disconnected'); 76 | clearInterval(interval); 77 | }); 78 | 79 | }); 80 | -------------------------------------------------------------------------------- /src/app/app.component.css: -------------------------------------------------------------------------------- 1 | .container { 2 | max-width: 1200px; 3 | margin: 100px auto; 4 | } 5 | 6 | .row { 7 | display: grid; 8 | grid-template-columns: 1fr 1fr; 9 | grid-gap: 20px; 10 | margin-bottom: 2rem; 11 | align-items: center; 12 | } 13 | 14 | ul { 15 | margin: 0; 16 | padding: 0; 17 | list-style: none; 18 | } 19 | 20 | li { 21 | margin-bottom: .5rem; 22 | padding-bottom: .5rem; 23 | border-bottom: 1px #eee solid; 24 | } 25 | 26 | li:last-child { 27 | margin-bottom: 0; 28 | padding-bottom: 0; 29 | border-bottom: 0 none; 30 | overflow: hidden; 31 | } 32 | 33 | form, .texts { 34 | align-self: start; 35 | } 36 | 37 | textarea { 38 | width: 100%; 39 | min-height: 120px; 40 | padding: 10px; 41 | box-sizing: border-box; 42 | } 43 | 44 | button { 45 | padding: 10px 15px; 46 | float: right; 47 | cursor: pointer; 48 | } 49 | 50 | button:disabled { 51 | cursor: default; 52 | } 53 | 54 | .counter { 55 | text-align: center; 56 | font-size: 24px; 57 | vertical-align: middle; 58 | } 59 | 60 | .remove { 61 | display: block; 62 | height: 16px; 63 | width: 16px; 64 | cursor: pointer; 65 | float: right; 66 | line-height: 16px; 67 | text-align: center; 68 | color: red; 69 | font-size: 12px; 70 | } 71 | -------------------------------------------------------------------------------- /src/app/app.component.html: -------------------------------------------------------------------------------- 1 |
2 |

Angular WebSocket Starter Demo

3 | 4 |
5 |
6 |
    7 |
  • 8 | №{{ message.id }}: {{ message.text }} 9 |
  • 10 |
11 |
12 | 13 |
14 | Update websocket counter: {{ counter }} 15 |
16 |
17 | 18 |
19 |
20 |
21 |
22 | 23 |
24 |
25 |
26 | 27 |
28 |
29 | 30 |
31 |
    32 |
  • 33 | {{ text }} 34 | x 35 |
  • 36 |
37 |
38 |
39 | 40 |
41 | -------------------------------------------------------------------------------- /src/app/app.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed, async } from '@angular/core/testing'; 2 | import { AppComponent } from './app.component'; 3 | 4 | describe('AppComponent', () => { 5 | beforeEach(async(() => { 6 | TestBed.configureTestingModule({ 7 | declarations: [ 8 | AppComponent 9 | ] 10 | }).compileComponents(); 11 | })); 12 | it('should create the app', async(() => { 13 | const fixture = TestBed.createComponent(AppComponent); 14 | const app = fixture.debugElement.componentInstance; 15 | expect(app).toBeTruthy(); 16 | })); 17 | }); 18 | -------------------------------------------------------------------------------- /src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { FormBuilder, FormGroup, Validators } from '@angular/forms'; 3 | import { Observable } from 'rxjs'; 4 | 5 | import { WebsocketService } from './websocket'; 6 | import { WS } from './websocket.events'; 7 | 8 | export interface IMessage { 9 | id: number; 10 | text: string; 11 | } 12 | 13 | 14 | @Component({ 15 | selector: 'app-root', 16 | templateUrl: './app.component.html', 17 | styleUrls: ['./app.component.css'] 18 | }) 19 | export class AppComponent implements OnInit { 20 | 21 | private messages$: Observable; 22 | private counter$: Observable; 23 | private texts$: Observable; 24 | 25 | public form: FormGroup; 26 | 27 | constructor(private fb: FormBuilder, private wsService: WebsocketService) { 28 | } 29 | 30 | ngOnInit() { 31 | this.form = this.fb.group({ 32 | text: [null, [ 33 | Validators.required 34 | ]] 35 | }); 36 | 37 | // get messages 38 | this.messages$ = this.wsService.on(WS.ON.MESSAGES); 39 | 40 | // get counter 41 | this.counter$ = this.wsService.on(WS.ON.COUNTER); 42 | 43 | // get texts 44 | this.texts$ = this.wsService.on(WS.ON.UPDATE_TEXTS); 45 | } 46 | 47 | public sendText(): void { 48 | if (this.form.valid) { 49 | this.wsService.send(WS.SEND.SEND_TEXT, this.form.value.text); 50 | this.form.reset(); 51 | } 52 | } 53 | 54 | public removeText(index: number): void { 55 | this.wsService.send(WS.SEND.REMOVE_TEXT, index); 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { BrowserModule } from '@angular/platform-browser'; 2 | import { NgModule } from '@angular/core'; 3 | import { ReactiveFormsModule } from '@angular/forms'; 4 | 5 | import { AppComponent } from './app.component'; 6 | import { WebsocketModule } from './websocket'; 7 | import { environment } from '../environments/environment'; 8 | 9 | 10 | @NgModule({ 11 | declarations: [ 12 | AppComponent 13 | ], 14 | imports: [ 15 | BrowserModule, 16 | ReactiveFormsModule, 17 | WebsocketModule.config({ 18 | url: environment.ws 19 | }) 20 | ], 21 | providers: [], 22 | bootstrap: [AppComponent] 23 | }) 24 | export class AppModule { 25 | } 26 | -------------------------------------------------------------------------------- /src/app/websocket.events.ts: -------------------------------------------------------------------------------- 1 | export const WS = { 2 | ON: { 3 | MESSAGES: 'messages', 4 | COUNTER: 'counter', 5 | UPDATE_TEXTS: 'update-texts' 6 | }, 7 | SEND: { 8 | SEND_TEXT: 'set-text', 9 | REMOVE_TEXT: 'remove-text' 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /src/app/websocket/index.ts: -------------------------------------------------------------------------------- 1 | export * from './websocket.module'; 2 | export * from './websocket.config'; 3 | export * from './websocket.interfaces'; 4 | export * from './websocket.service'; 5 | -------------------------------------------------------------------------------- /src/app/websocket/websocket.config.ts: -------------------------------------------------------------------------------- 1 | import { InjectionToken } from '@angular/core'; 2 | 3 | export const config: InjectionToken = new InjectionToken('websocket'); 4 | -------------------------------------------------------------------------------- /src/app/websocket/websocket.interfaces.ts: -------------------------------------------------------------------------------- 1 | import { Observable } from 'rxjs'; 2 | 3 | export interface IWebsocketService { 4 | on(event: string): Observable; 5 | send(event: string, data: any): void; 6 | status: Observable; 7 | } 8 | 9 | export interface WebSocketConfig { 10 | url: string; 11 | reconnectInterval?: number; 12 | reconnectAttempts?: number; 13 | } 14 | 15 | export interface IWsMessage { 16 | event: string; 17 | data: T; 18 | } 19 | -------------------------------------------------------------------------------- /src/app/websocket/websocket.module.spec.ts: -------------------------------------------------------------------------------- 1 | import { WebsocketModule } from './websocket.module'; 2 | 3 | describe('WebsocketModule', () => { 4 | let websocketModule: WebsocketModule; 5 | 6 | beforeEach(() => { 7 | websocketModule = new WebsocketModule(); 8 | }); 9 | 10 | it('should create an instance', () => { 11 | expect(websocketModule).toBeTruthy(); 12 | }); 13 | }); 14 | -------------------------------------------------------------------------------- /src/app/websocket/websocket.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule, ModuleWithProviders } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | 4 | import { WebsocketService } from './websocket.service'; 5 | import { config } from './websocket.config'; 6 | import { WebSocketConfig } from './websocket.interfaces'; 7 | 8 | 9 | @NgModule({ 10 | imports: [ 11 | CommonModule 12 | ], 13 | declarations: [], 14 | providers: [ 15 | WebsocketService 16 | ] 17 | }) 18 | export class WebsocketModule { 19 | public static config(wsConfig: WebSocketConfig): ModuleWithProviders { 20 | return { 21 | ngModule: WebsocketModule, 22 | providers: [{ provide: config, useValue: wsConfig }] 23 | }; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/app/websocket/websocket.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed, inject } from '@angular/core/testing'; 2 | 3 | import { WebsocketService } from './websocket.service'; 4 | 5 | describe('WebsocketService', () => { 6 | beforeEach(() => { 7 | TestBed.configureTestingModule({ 8 | providers: [WebsocketService] 9 | }); 10 | }); 11 | 12 | it('should be created', inject([WebsocketService], (service: WebsocketService) => { 13 | expect(service).toBeTruthy(); 14 | })); 15 | }); 16 | -------------------------------------------------------------------------------- /src/app/websocket/websocket.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, OnDestroy, Inject } from '@angular/core'; 2 | import { Observable, SubscriptionLike, Subject, Observer, interval } from 'rxjs'; 3 | import { filter, map } from 'rxjs/operators'; 4 | import { WebSocketSubject, WebSocketSubjectConfig } from 'rxjs/webSocket'; 5 | 6 | import { share, distinctUntilChanged, takeWhile } from 'rxjs/operators'; 7 | import { IWebsocketService, IWsMessage, WebSocketConfig } from './websocket.interfaces'; 8 | import { config } from './websocket.config'; 9 | 10 | 11 | @Injectable({ 12 | providedIn: 'root' 13 | }) 14 | export class WebsocketService implements IWebsocketService, OnDestroy { 15 | 16 | private config: WebSocketSubjectConfig>; 17 | 18 | private websocketSub: SubscriptionLike; 19 | private statusSub: SubscriptionLike; 20 | 21 | private reconnection$: Observable; 22 | private websocket$: WebSocketSubject>; 23 | private connection$: Observer; 24 | private wsMessages$: Subject>; 25 | 26 | private reconnectInterval: number; 27 | private reconnectAttempts: number; 28 | private isConnected: boolean; 29 | 30 | 31 | public status: Observable; 32 | 33 | constructor(@Inject(config) private wsConfig: WebSocketConfig) { 34 | this.wsMessages$ = new Subject>(); 35 | 36 | this.reconnectInterval = wsConfig.reconnectInterval || 5000; // pause between connections 37 | this.reconnectAttempts = wsConfig.reconnectAttempts || 10; // number of connection attempts 38 | 39 | this.config = { 40 | url: wsConfig.url, 41 | closeObserver: { 42 | next: (event: CloseEvent) => { 43 | this.websocket$ = null; 44 | this.connection$.next(false); 45 | } 46 | }, 47 | openObserver: { 48 | next: (event: Event) => { 49 | console.log('WebSocket connected!'); 50 | this.connection$.next(true); 51 | } 52 | } 53 | }; 54 | 55 | // connection status 56 | this.status = new Observable((observer) => { 57 | this.connection$ = observer; 58 | }).pipe(share(), distinctUntilChanged()); 59 | 60 | // run reconnect if not connection 61 | this.statusSub = this.status 62 | .subscribe((isConnected) => { 63 | this.isConnected = isConnected; 64 | 65 | if (!this.reconnection$ && typeof(isConnected) === 'boolean' && !isConnected) { 66 | this.reconnect(); 67 | } 68 | }); 69 | 70 | this.websocketSub = this.wsMessages$.subscribe( 71 | null, (error: ErrorEvent) => console.error('WebSocket error!', error) 72 | ); 73 | 74 | this.connect(); 75 | } 76 | 77 | ngOnDestroy() { 78 | this.websocketSub.unsubscribe(); 79 | this.statusSub.unsubscribe(); 80 | } 81 | 82 | 83 | /* 84 | * connect to WebSocked 85 | * */ 86 | private connect(): void { 87 | this.websocket$ = new WebSocketSubject(this.config); 88 | 89 | this.websocket$.subscribe( 90 | (message) => this.wsMessages$.next(message), 91 | (error: Event) => { 92 | if (!this.websocket$) { 93 | // run reconnect if errors 94 | this.reconnect(); 95 | } 96 | }); 97 | } 98 | 99 | 100 | /* 101 | * reconnect if not connecting or errors 102 | * */ 103 | private reconnect(): void { 104 | this.reconnection$ = interval(this.reconnectInterval) 105 | .pipe(takeWhile((v, index) => index < this.reconnectAttempts && !this.websocket$)); 106 | 107 | this.reconnection$.subscribe( 108 | () => this.connect(), 109 | null, 110 | () => { 111 | // Subject complete if reconnect attemts ending 112 | this.reconnection$ = null; 113 | 114 | if (!this.websocket$) { 115 | this.wsMessages$.complete(); 116 | this.connection$.complete(); 117 | } 118 | }); 119 | } 120 | 121 | 122 | /* 123 | * on message event 124 | * */ 125 | public on(event: string): Observable { 126 | if (event) { 127 | return this.wsMessages$.pipe( 128 | filter((message: IWsMessage) => message.event === event), 129 | map((message: IWsMessage) => message.data) 130 | ); 131 | } 132 | } 133 | 134 | 135 | /* 136 | * on message to server 137 | * */ 138 | public send(event: string, data: any = {}): void { 139 | if (event && this.isConnected) { 140 | this.websocket$.next(JSON.stringify({ event, data })); 141 | } else { 142 | console.error('Send error!'); 143 | } 144 | } 145 | 146 | } 147 | -------------------------------------------------------------------------------- /src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlexDaSoul/angular-websocket-starter/373ff0d009ecffb92920c45e097beac1e5ee8dd8/src/assets/.gitkeep -------------------------------------------------------------------------------- /src/browserslist: -------------------------------------------------------------------------------- 1 | # This file is currently used by autoprefixer to adjust CSS to support the below specified browsers 2 | # For additional information regarding the format and rule options, please see: 3 | # https://github.com/browserslist/browserslist#queries 4 | # For IE 9-11 support, please uncomment the last line of the file and adjust as needed 5 | > 0.5% 6 | last 2 versions 7 | Firefox ESR 8 | not dead 9 | # IE 9-11 -------------------------------------------------------------------------------- /src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true, 3 | ws: 'ws://localhost:6759' 4 | }; 5 | -------------------------------------------------------------------------------- /src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // This file can be replaced during build by using the `fileReplacements` array. 2 | // `ng build ---prod` replaces `environment.ts` with `environment.prod.ts`. 3 | // The list of file replacements can be found in `angular.json`. 4 | 5 | export const environment = { 6 | production: false, 7 | ws: 'ws://localhost:6759' 8 | }; 9 | 10 | /* 11 | * In development mode, to ignore zone related error stack frames such as 12 | * `zone.run`, `zoneDelegate.invokeTask` for easier debugging, you can 13 | * import the following file, but please comment it out in production mode 14 | * because it will have performance impact when throw error 15 | */ 16 | // import 'zone.js/dist/zone-error'; // Included with Angular CLI. 17 | -------------------------------------------------------------------------------- /src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlexDaSoul/angular-websocket-starter/373ff0d009ecffb92920c45e097beac1e5ee8dd8/src/favicon.ico -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Angular Websocket Starter 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/karma.conf.js: -------------------------------------------------------------------------------- 1 | // Karma configuration file, see link for more information 2 | // https://karma-runner.github.io/1.0/config/configuration-file.html 3 | 4 | module.exports = function(config) { 5 | config.set({ 6 | basePath: '', 7 | frameworks: ['jasmine', '@angular-devkit/build-angular'], 8 | plugins: [ 9 | require('karma-jasmine'), 10 | require('karma-chrome-launcher'), 11 | require('karma-jasmine-html-reporter'), 12 | require('karma-coverage-istanbul-reporter'), 13 | require('@angular-devkit/build-angular/plugins/karma') 14 | ], 15 | client: { 16 | clearContext: false // leave Jasmine Spec Runner output visible in browser 17 | }, 18 | coverageIstanbulReporter: { 19 | dir: require('path').join(__dirname, '../coverage'), 20 | reports: ['html', 'lcovonly'], 21 | fixWebpackSourcePaths: true 22 | }, 23 | reporters: ['progress', 'kjhtml'], 24 | port: 9876, 25 | colors: true, 26 | logLevel: config.LOG_INFO, 27 | autoWatch: true, 28 | browsers: ['Chrome'], 29 | singleRun: false 30 | }); 31 | }; -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { enableProdMode } from '@angular/core'; 2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 3 | 4 | import { AppModule } from './app/app.module'; 5 | import { environment } from './environments/environment'; 6 | 7 | if (environment.production) { 8 | enableProdMode(); 9 | } 10 | 11 | platformBrowserDynamic().bootstrapModule(AppModule) 12 | .catch(err => console.log(err)); 13 | -------------------------------------------------------------------------------- /src/polyfills.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file includes polyfills needed by Angular and is loaded before the app. 3 | * You can add your own extra polyfills to this file. 4 | * 5 | * This file is divided into 2 sections: 6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. 7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main 8 | * file. 9 | * 10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that 11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), 12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. 13 | * 14 | * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** IE9, IE10 and IE11 requires all of the following polyfills. **/ 22 | // import 'core-js/es6/symbol'; 23 | // import 'core-js/es6/object'; 24 | // import 'core-js/es6/function'; 25 | // import 'core-js/es6/parse-int'; 26 | // import 'core-js/es6/parse-float'; 27 | // import 'core-js/es6/number'; 28 | // import 'core-js/es6/math'; 29 | // import 'core-js/es6/string'; 30 | // import 'core-js/es6/date'; 31 | // import 'core-js/es6/array'; 32 | // import 'core-js/es6/regexp'; 33 | // import 'core-js/es6/map'; 34 | // import 'core-js/es6/weak-map'; 35 | // import 'core-js/es6/set'; 36 | 37 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 38 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 39 | 40 | /** IE10 and IE11 requires the following for the Reflect API. */ 41 | // import 'core-js/es6/reflect'; 42 | 43 | 44 | /** Evergreen browsers require these. **/ 45 | // Used for reflect-metadata in JIT. If you use AOT (and only Angular decorators), you can remove. 46 | import 'core-js/es7/reflect'; 47 | 48 | 49 | /** 50 | * Web Animations `@angular/platform-browser/animations` 51 | * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. 52 | * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). 53 | **/ 54 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 55 | 56 | /** 57 | * By default, zone.js will patch all possible macroTask and DomEvents 58 | * user can disable parts of macroTask/DomEvents patch by setting following flags 59 | */ 60 | 61 | // (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame 62 | // (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick 63 | // (window as any).__zone_symbol__BLACK_LISTED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames 64 | 65 | /* 66 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js 67 | * with the following flag, it will bypass `zone.js` patch for IE/Edge 68 | */ 69 | // (window as any).__Zone_enable_cross_context_check = true; 70 | 71 | /*************************************************************************************************** 72 | * Zone JS is required by default for Angular itself. 73 | */ 74 | import 'zone.js/dist/zone'; // Included with Angular CLI. 75 | 76 | 77 | /*************************************************************************************************** 78 | * APPLICATION IMPORTS 79 | */ 80 | -------------------------------------------------------------------------------- /src/styles.css: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | -------------------------------------------------------------------------------- /src/test.ts: -------------------------------------------------------------------------------- 1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files 2 | 3 | import 'zone.js/dist/zone-testing'; 4 | import { getTestBed } from '@angular/core/testing'; 5 | import { 6 | BrowserDynamicTestingModule, 7 | platformBrowserDynamicTesting 8 | } from '@angular/platform-browser-dynamic/testing'; 9 | 10 | declare const require: any; 11 | 12 | // First, initialize the Angular testing environment. 13 | getTestBed().initTestEnvironment( 14 | BrowserDynamicTestingModule, 15 | platformBrowserDynamicTesting() 16 | ); 17 | // Then we find all the tests. 18 | const context = require.context('./', true, /\.spec\.ts$/); 19 | // And load the modules. 20 | context.keys().map(context); 21 | -------------------------------------------------------------------------------- /src/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "module": "es2015", 6 | "types": [] 7 | }, 8 | "exclude": [ 9 | "src/test.ts", 10 | "**/*.spec.ts" 11 | ] 12 | } 13 | -------------------------------------------------------------------------------- /src/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/spec", 5 | "module": "commonjs", 6 | "types": [ 7 | "jasmine", 8 | "node" 9 | ] 10 | }, 11 | "files": [ 12 | "test.ts", 13 | "polyfills.ts" 14 | ], 15 | "include": [ 16 | "**/*.spec.ts", 17 | "**/*.d.ts" 18 | ] 19 | } 20 | -------------------------------------------------------------------------------- /src/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tslint.json", 3 | "rules": { 4 | "directive-selector": [ 5 | true, 6 | "attribute", 7 | "app", 8 | "camelCase" 9 | ], 10 | "component-selector": [ 11 | true, 12 | "element", 13 | "app", 14 | "kebab-case" 15 | ] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "baseUrl": "./", 5 | "outDir": "./dist/out-tsc", 6 | "sourceMap": true, 7 | "declaration": false, 8 | "moduleResolution": "node", 9 | "emitDecoratorMetadata": true, 10 | "experimentalDecorators": true, 11 | "target": "es5", 12 | "typeRoots": [ 13 | "node_modules/@types" 14 | ], 15 | "lib": [ 16 | "es2017", 17 | "dom" 18 | ] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "rulesDirectory": [ 3 | "node_modules/codelyzer" 4 | ], 5 | "rules": { 6 | "arrow-return-shorthand": true, 7 | "callable-types": true, 8 | "class-name": true, 9 | "comment-format": [ 10 | true, 11 | "check-space" 12 | ], 13 | "curly": true, 14 | "deprecation": { 15 | "severity": "warn" 16 | }, 17 | "eofline": true, 18 | "forin": true, 19 | "import-blacklist": [ 20 | true, 21 | "rxjs/Rx" 22 | ], 23 | "import-spacing": true, 24 | "indent": [ 25 | true, 26 | "spaces" 27 | ], 28 | "interface-over-type-literal": true, 29 | "label-position": true, 30 | "max-line-length": [ 31 | true, 32 | 140 33 | ], 34 | "member-access": false, 35 | "member-ordering": [ 36 | true, 37 | { 38 | "order": [ 39 | "static-field", 40 | "instance-field", 41 | "static-method", 42 | "instance-method" 43 | ] 44 | } 45 | ], 46 | "no-arg": true, 47 | "no-bitwise": true, 48 | "no-console": [ 49 | true, 50 | "debug", 51 | "info", 52 | "time", 53 | "timeEnd", 54 | "trace" 55 | ], 56 | "no-construct": true, 57 | "no-debugger": true, 58 | "no-duplicate-super": true, 59 | "no-empty": false, 60 | "no-empty-interface": true, 61 | "no-eval": true, 62 | "no-inferrable-types": [ 63 | true, 64 | "ignore-params" 65 | ], 66 | "no-misused-new": true, 67 | "no-non-null-assertion": true, 68 | "no-shadowed-variable": true, 69 | "no-string-literal": false, 70 | "no-string-throw": true, 71 | "no-switch-case-fall-through": true, 72 | "no-trailing-whitespace": true, 73 | "no-unnecessary-initializer": true, 74 | "no-unused-expression": true, 75 | "no-use-before-declare": true, 76 | "no-var-keyword": true, 77 | "object-literal-sort-keys": false, 78 | "one-line": [ 79 | true, 80 | "check-open-brace", 81 | "check-catch", 82 | "check-else", 83 | "check-whitespace" 84 | ], 85 | "prefer-const": true, 86 | "quotemark": [ 87 | true, 88 | "single" 89 | ], 90 | "radix": true, 91 | "semicolon": [ 92 | true, 93 | "always" 94 | ], 95 | "triple-equals": [ 96 | true, 97 | "allow-null-check" 98 | ], 99 | "typedef-whitespace": [ 100 | true, 101 | { 102 | "call-signature": "nospace", 103 | "index-signature": "nospace", 104 | "parameter": "nospace", 105 | "property-declaration": "nospace", 106 | "variable-declaration": "nospace" 107 | } 108 | ], 109 | "unified-signatures": true, 110 | "variable-name": false, 111 | "whitespace": [ 112 | true, 113 | "check-branch", 114 | "check-decl", 115 | "check-operator", 116 | "check-separator", 117 | "check-type" 118 | ], 119 | "no-output-on-prefix": true, 120 | "use-input-property-decorator": true, 121 | "use-output-property-decorator": true, 122 | "use-host-property-decorator": true, 123 | "no-input-rename": true, 124 | "no-output-rename": true, 125 | "use-life-cycle-interface": true, 126 | "use-pipe-transform-interface": true, 127 | "component-class-suffix": true, 128 | "directive-class-suffix": true 129 | } 130 | } 131 | --------------------------------------------------------------------------------