├── .angular-cli.json ├── .editorconfig ├── .gitignore ├── LICENSE.txt ├── README.md ├── app.js ├── bin └── www ├── e2e ├── app.e2e-spec.ts ├── app.po.ts └── tsconfig.e2e.json ├── karma.conf.js ├── models └── Chat.js ├── package.json ├── protractor.conf.js ├── routes └── chat.js ├── src ├── app │ ├── app.component.css │ ├── app.component.html │ ├── app.component.spec.ts │ ├── app.component.ts │ ├── app.module.ts │ ├── chat.service.spec.ts │ ├── chat.service.ts │ └── chat │ │ ├── chat.component.css │ │ ├── chat.component.html │ │ ├── chat.component.spec.ts │ │ └── chat.component.ts ├── assets │ └── .gitkeep ├── environments │ ├── environment.prod.ts │ └── environment.ts ├── favicon.ico ├── index.html ├── main.ts ├── polyfills.ts ├── styles.css ├── test.ts ├── tsconfig.app.json ├── tsconfig.spec.json └── typings.d.ts ├── tsconfig.json └── tslint.json /.angular-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "project": { 4 | "name": "mean-chat" 5 | }, 6 | "apps": [ 7 | { 8 | "root": "src", 9 | "outDir": "dist", 10 | "assets": [ 11 | "assets", 12 | "favicon.ico" 13 | ], 14 | "index": "index.html", 15 | "main": "main.ts", 16 | "polyfills": "polyfills.ts", 17 | "test": "test.ts", 18 | "tsconfig": "tsconfig.app.json", 19 | "testTsconfig": "tsconfig.spec.json", 20 | "prefix": "app", 21 | "styles": [ 22 | "styles.css" 23 | ], 24 | "scripts": [], 25 | "environmentSource": "environments/environment.ts", 26 | "environments": { 27 | "dev": "environments/environment.ts", 28 | "prod": "environments/environment.prod.ts" 29 | } 30 | } 31 | ], 32 | "e2e": { 33 | "protractor": { 34 | "config": "./protractor.conf.js" 35 | } 36 | }, 37 | "lint": [ 38 | { 39 | "project": "src/tsconfig.app.json" 40 | }, 41 | { 42 | "project": "src/tsconfig.spec.json" 43 | }, 44 | { 45 | "project": "e2e/tsconfig.e2e.json" 46 | } 47 | ], 48 | "test": { 49 | "karma": { 50 | "config": "./karma.conf.js" 51 | } 52 | }, 53 | "defaults": { 54 | "styleExt": "css", 55 | "component": {} 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see http://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 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 | testem.log 34 | /typings 35 | 36 | # e2e 37 | /e2e/*.js 38 | /e2e/*.map 39 | 40 | # System Files 41 | .DS_Store 42 | Thumbs.db 43 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Didin Jamaludin 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 | # mean-angular4-chat-app 2 | 3 | This source code is part of tutorial [Building Chat Application using MEAN Stack (Angular 4) and Socket.io](https://www.djamware.com/post/58e0d15280aca75cdc948e4e/building-chat-application-using-mean-stack-angular-4-and-socketio) 4 | 5 | Step to run: 6 | 7 | * Prepare Node.js and Angular CLI 8 | * Clone this repo 9 | * Run 'npm install' 10 | * Run 'ng build --prod' 11 | * Run 'nodemon' or 'npm start' 12 | 13 | If you think this source code is useful, it will be great if you just give it star or just buy me a cup of cofee [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=Q5WK24UVWUGBN) 14 | -------------------------------------------------------------------------------- /app.js: -------------------------------------------------------------------------------- 1 | var express = require('express'); 2 | var path = require('path'); 3 | var favicon = require('serve-favicon'); 4 | var logger = require('morgan'); 5 | var bodyParser = require('body-parser'); 6 | var mongoose = require('mongoose'); 7 | 8 | mongoose.Promise = global.Promise; 9 | 10 | mongoose.connect('mongodb://localhost/mean-chat') 11 | .then(() => console.log('connection successful')) 12 | .catch((err) => console.error(err)); 13 | 14 | var chat = require('./routes/chat'); 15 | var app = express(); 16 | 17 | app.set('view engine', 'html'); 18 | app.use(logger('dev')); 19 | app.use(bodyParser.json()); 20 | app.use(bodyParser.urlencoded({'extended':'false'})); 21 | app.use(express.static(path.join(__dirname, 'dist'))); 22 | 23 | app.use('/chat', chat); 24 | 25 | // catch 404 and forward to error handler 26 | app.use(function(req, res, next) { 27 | var err = new Error('Not Found'); 28 | err.status = 404; 29 | next(err); 30 | }); 31 | 32 | // error handler 33 | app.use(function(err, req, res, next) { 34 | // set locals, only providing error in development 35 | res.locals.message = err.message; 36 | res.locals.error = req.app.get('env') === 'development' ? err : {}; 37 | 38 | // render the error page 39 | res.status(err.status || 500); 40 | res.render('error'); 41 | }); 42 | 43 | module.exports = app; 44 | -------------------------------------------------------------------------------- /bin/www: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | /** 4 | * Module dependencies. 5 | */ 6 | 7 | var app = require('../app'); 8 | var debug = require('debug')('mean-app:server'); 9 | var http = require('http'); 10 | 11 | /** 12 | * Get port from environment and store in Express. 13 | */ 14 | 15 | var port = normalizePort(process.env.PORT || '3000'); 16 | app.set('port', port); 17 | 18 | /** 19 | * Create HTTP server. 20 | */ 21 | 22 | var server = http.createServer(app); 23 | 24 | /** 25 | * Listen on provided port, on all network interfaces. 26 | */ 27 | 28 | server.listen(port); 29 | server.on('error', onError); 30 | server.on('listening', onListening); 31 | 32 | /** 33 | * Normalize a port into a number, string, or false. 34 | */ 35 | 36 | function normalizePort(val) { 37 | var port = parseInt(val, 10); 38 | 39 | if (isNaN(port)) { 40 | // named pipe 41 | return val; 42 | } 43 | 44 | if (port >= 0) { 45 | // port number 46 | return port; 47 | } 48 | 49 | return false; 50 | } 51 | 52 | /** 53 | * Event listener for HTTP server "error" event. 54 | */ 55 | 56 | function onError(error) { 57 | if (error.syscall !== 'listen') { 58 | throw error; 59 | } 60 | 61 | var bind = typeof port === 'string' 62 | ? 'Pipe ' + port 63 | : 'Port ' + port; 64 | 65 | // handle specific listen errors with friendly messages 66 | switch (error.code) { 67 | case 'EACCES': 68 | console.error(bind + ' requires elevated privileges'); 69 | process.exit(1); 70 | break; 71 | case 'EADDRINUSE': 72 | console.error(bind + ' is already in use'); 73 | process.exit(1); 74 | break; 75 | default: 76 | throw error; 77 | } 78 | } 79 | 80 | /** 81 | * Event listener for HTTP server "listening" event. 82 | */ 83 | 84 | function onListening() { 85 | var addr = server.address(); 86 | var bind = typeof addr === 'string' 87 | ? 'pipe ' + addr 88 | : 'port ' + addr.port; 89 | debug('Listening on ' + bind); 90 | } 91 | -------------------------------------------------------------------------------- /e2e/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { MeanChatPage } from './app.po'; 2 | 3 | describe('mean-chat App', () => { 4 | let page: MeanChatPage; 5 | 6 | beforeEach(() => { 7 | page = new MeanChatPage(); 8 | }); 9 | 10 | it('should display message saying app works', () => { 11 | page.navigateTo(); 12 | expect(page.getParagraphText()).toEqual('app works!'); 13 | }); 14 | }); 15 | -------------------------------------------------------------------------------- /e2e/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, element, by } from 'protractor'; 2 | 3 | export class MeanChatPage { 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/e2e", 5 | "module": "commonjs", 6 | "target": "es5", 7 | "types":[ 8 | "jasmine", 9 | "node" 10 | ] 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /karma.conf.js: -------------------------------------------------------------------------------- 1 | // Karma configuration file, see link for more information 2 | // https://karma-runner.github.io/0.13/config/configuration-file.html 3 | 4 | module.exports = function (config) { 5 | config.set({ 6 | basePath: '', 7 | frameworks: ['jasmine', '@angular/cli'], 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/cli/plugins/karma') 14 | ], 15 | client:{ 16 | clearContext: false // leave Jasmine Spec Runner output visible in browser 17 | }, 18 | files: [ 19 | { pattern: './src/test.ts', watched: false } 20 | ], 21 | preprocessors: { 22 | './src/test.ts': ['@angular/cli'] 23 | }, 24 | mime: { 25 | 'text/x-typescript': ['ts','tsx'] 26 | }, 27 | coverageIstanbulReporter: { 28 | reports: [ 'html', 'lcovonly' ], 29 | fixWebpackSourcePaths: true 30 | }, 31 | angularCli: { 32 | environment: 'dev' 33 | }, 34 | reporters: config.angularCli && config.angularCli.codeCoverage 35 | ? ['progress', 'coverage-istanbul'] 36 | : ['progress', 'kjhtml'], 37 | port: 9876, 38 | colors: true, 39 | logLevel: config.LOG_INFO, 40 | autoWatch: true, 41 | browsers: ['Chrome'], 42 | singleRun: false 43 | }); 44 | }; 45 | -------------------------------------------------------------------------------- /models/Chat.js: -------------------------------------------------------------------------------- 1 | var mongoose = require('mongoose'); 2 | 3 | var ChatSchema = new mongoose.Schema({ 4 | room: String, 5 | nickname: String, 6 | message: String, 7 | updated_at: { type: Date, default: Date.now }, 8 | }); 9 | 10 | module.exports = mongoose.model('Chat', ChatSchema); 11 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "mean-chat", 3 | "version": "0.0.0", 4 | "license": "MIT", 5 | "scripts": { 6 | "ng": "ng", 7 | "start": "node ./bin/www", 8 | "build": "ng build", 9 | "test": "ng test", 10 | "lint": "ng lint", 11 | "e2e": "ng e2e" 12 | }, 13 | "private": true, 14 | "dependencies": { 15 | "@angular/common": "^4.0.0", 16 | "@angular/compiler": "^4.0.0", 17 | "@angular/core": "^4.0.0", 18 | "@angular/forms": "^4.0.0", 19 | "@angular/http": "^4.0.0", 20 | "@angular/platform-browser": "^4.0.0", 21 | "@angular/platform-browser-dynamic": "^4.0.0", 22 | "@angular/router": "^4.0.0", 23 | "body-parser": "^1.17.1", 24 | "core-js": "^2.4.1", 25 | "express": "^4.15.2", 26 | "mongoose": "^4.9.2", 27 | "morgan": "^1.8.1", 28 | "rxjs": "^5.1.0", 29 | "serve-favicon": "^2.4.2", 30 | "socket.io-client": "^1.7.3", 31 | "socketio": "^1.0.0", 32 | "zone.js": "^0.8.4" 33 | }, 34 | "devDependencies": { 35 | "@angular/cli": "1.0.0", 36 | "@angular/compiler-cli": "^4.0.0", 37 | "@types/jasmine": "2.5.38", 38 | "@types/node": "~6.0.60", 39 | "codelyzer": "~2.0.0", 40 | "jasmine-core": "~2.5.2", 41 | "jasmine-spec-reporter": "~3.2.0", 42 | "karma": "~1.4.1", 43 | "karma-chrome-launcher": "~2.0.0", 44 | "karma-cli": "~1.0.1", 45 | "karma-jasmine": "~1.1.0", 46 | "karma-jasmine-html-reporter": "^0.2.2", 47 | "karma-coverage-istanbul-reporter": "^0.2.0", 48 | "protractor": "~5.1.0", 49 | "ts-node": "~2.0.0", 50 | "tslint": "~4.5.0", 51 | "typescript": "~2.2.0" 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /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 | './e2e/**/*.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 | beforeLaunch: function() { 23 | require('ts-node').register({ 24 | project: 'e2e/tsconfig.e2e.json' 25 | }); 26 | }, 27 | onPrepare() { 28 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /routes/chat.js: -------------------------------------------------------------------------------- 1 | var express = require('express'); 2 | var router = express.Router(); 3 | var mongoose = require('mongoose'); 4 | var app = express(); 5 | var server = require('http').createServer(app); 6 | var io = require('socket.io')(server); 7 | var Chat = require('../models/Chat.js'); 8 | 9 | server.listen(4000); 10 | 11 | // socket io 12 | io.on('connection', function (socket) { 13 | console.log('User connected'); 14 | socket.on('disconnect', function() { 15 | console.log('User disconnected'); 16 | }); 17 | socket.on('save-message', function (data) { 18 | console.log(data); 19 | io.emit('new-message', { message: data }); 20 | }); 21 | }); 22 | 23 | /* GET ALL CHATS */ 24 | router.get('/:room', function(req, res, next) { 25 | Chat.find({ room: req.params.room }, function (err, chats) { 26 | if (err) return next(err); 27 | res.json(chats); 28 | }); 29 | }); 30 | 31 | /* GET SINGLE CHAT BY ID */ 32 | router.get('/:id', function(req, res, next) { 33 | Chat.findById(req.params.id, function (err, post) { 34 | if (err) return next(err); 35 | res.json(post); 36 | }); 37 | }); 38 | 39 | /* SAVE CHAT */ 40 | router.post('/', function(req, res, next) { 41 | Chat.create(req.body, function (err, post) { 42 | if (err) return next(err); 43 | res.json(post); 44 | }); 45 | }); 46 | 47 | /* UPDATE CHAT */ 48 | router.put('/:id', function(req, res, next) { 49 | Chat.findByIdAndUpdate(req.params.id, req.body, function (err, post) { 50 | if (err) return next(err); 51 | res.json(post); 52 | }); 53 | }); 54 | 55 | /* DELETE CHAT */ 56 | router.delete('/:id', function(req, res, next) { 57 | Chat.findByIdAndRemove(req.params.id, req.body, function (err, post) { 58 | if (err) return next(err); 59 | res.json(post); 60 | }); 61 | }); 62 | 63 | module.exports = router; 64 | -------------------------------------------------------------------------------- /src/app/app.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didinj/mean-angular4-chat-app/bbb053a022681cf00af802ea55ee38387867cc7b/src/app/app.component.css -------------------------------------------------------------------------------- /src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /src/app/app.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed, async } from '@angular/core/testing'; 2 | 3 | import { AppComponent } from './app.component'; 4 | 5 | describe('AppComponent', () => { 6 | beforeEach(async(() => { 7 | TestBed.configureTestingModule({ 8 | declarations: [ 9 | AppComponent 10 | ], 11 | }).compileComponents(); 12 | })); 13 | 14 | it('should create the app', async(() => { 15 | const fixture = TestBed.createComponent(AppComponent); 16 | const app = fixture.debugElement.componentInstance; 17 | expect(app).toBeTruthy(); 18 | })); 19 | 20 | it(`should have as title 'app works!'`, async(() => { 21 | const fixture = TestBed.createComponent(AppComponent); 22 | const app = fixture.debugElement.componentInstance; 23 | expect(app.title).toEqual('app works!'); 24 | })); 25 | 26 | it('should render title in a h1 tag', async(() => { 27 | const fixture = TestBed.createComponent(AppComponent); 28 | fixture.detectChanges(); 29 | const compiled = fixture.debugElement.nativeElement; 30 | expect(compiled.querySelector('h1').textContent).toContain('app works!'); 31 | })); 32 | }); 33 | -------------------------------------------------------------------------------- /src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-root', 5 | templateUrl: './app.component.html', 6 | styleUrls: ['./app.component.css'] 7 | }) 8 | export class AppComponent { 9 | title = 'app works!'; 10 | } 11 | -------------------------------------------------------------------------------- /src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { BrowserModule } from '@angular/platform-browser'; 2 | import { NgModule } from '@angular/core'; 3 | import { FormsModule } from '@angular/forms'; 4 | import { HttpModule } from '@angular/http'; 5 | import { RouterModule } from '@angular/router'; 6 | import { HashLocationStrategy, LocationStrategy } from '@angular/common'; 7 | 8 | import { AppComponent } from './app.component'; 9 | import { ChatService } from './chat.service'; 10 | import { ChatComponent } from './chat/chat.component'; 11 | 12 | const ROUTES = [ 13 | { path: '', redirectTo: 'chats', pathMatch: 'full' }, 14 | { path: 'chats', component: ChatComponent } 15 | ]; 16 | 17 | @NgModule({ 18 | declarations: [ 19 | AppComponent, 20 | ChatComponent 21 | ], 22 | imports: [ 23 | BrowserModule, 24 | FormsModule, 25 | HttpModule, 26 | RouterModule.forRoot(ROUTES) 27 | ], 28 | providers: [ 29 | ChatService, 30 | {provide: LocationStrategy, useClass: HashLocationStrategy} 31 | ], 32 | bootstrap: [AppComponent] 33 | }) 34 | export class AppModule { } 35 | -------------------------------------------------------------------------------- /src/app/chat.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed, inject } from '@angular/core/testing'; 2 | 3 | import { ChatService } from './chat.service'; 4 | 5 | describe('ChatService', () => { 6 | beforeEach(() => { 7 | TestBed.configureTestingModule({ 8 | providers: [ChatService] 9 | }); 10 | }); 11 | 12 | it('should ...', inject([ChatService], (service: ChatService) => { 13 | expect(service).toBeTruthy(); 14 | })); 15 | }); 16 | -------------------------------------------------------------------------------- /src/app/chat.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Http, Headers } from '@angular/http'; 3 | import 'rxjs/add/operator/map'; 4 | 5 | @Injectable() 6 | export class ChatService { 7 | 8 | constructor(private http: Http) { } 9 | 10 | getChatByRoom(room) { 11 | return new Promise((resolve, reject) => { 12 | this.http.get('/chat/' + room) 13 | .map(res => res.json()) 14 | .subscribe(res => { 15 | resolve(res); 16 | }, (err) => { 17 | reject(err); 18 | }); 19 | }); 20 | } 21 | 22 | showChat(id) { 23 | return new Promise((resolve, reject) => { 24 | this.http.get('/chat/' + id) 25 | .map(res => res.json()) 26 | .subscribe(res => { 27 | resolve(res) 28 | }, (err) => { 29 | reject(err); 30 | }); 31 | }); 32 | } 33 | 34 | saveChat(data) { 35 | return new Promise((resolve, reject) => { 36 | this.http.post('/chat', data) 37 | .map(res => res.json()) 38 | .subscribe(res => { 39 | resolve(res); 40 | }, (err) => { 41 | reject(err); 42 | }); 43 | }); 44 | } 45 | 46 | updateChat(id, data) { 47 | return new Promise((resolve, reject) => { 48 | this.http.put('/chat/'+id, data) 49 | .map(res => res.json()) 50 | .subscribe(res => { 51 | resolve(res); 52 | }, (err) => { 53 | reject(err); 54 | }); 55 | }); 56 | } 57 | 58 | deleteChat(id) { 59 | return new Promise((resolve, reject) => { 60 | this.http.delete('/chat/'+id) 61 | .subscribe(res => { 62 | resolve(res); 63 | }, (err) => { 64 | reject(err); 65 | }); 66 | }); 67 | } 68 | 69 | private handleError(error: any): Promise { 70 | return Promise.reject(error.message || error); 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /src/app/chat/chat.component.css: -------------------------------------------------------------------------------- 1 | .chat 2 | { 3 | list-style: none; 4 | margin: 0; 5 | padding: 0; 6 | } 7 | 8 | .chat li 9 | { 10 | margin-bottom: 10px; 11 | padding-bottom: 5px; 12 | border-bottom: 1px dotted #B3A9A9; 13 | } 14 | 15 | .chat li.left .chat-body 16 | { 17 | margin-left: 60px; 18 | } 19 | 20 | .chat li.right .chat-body 21 | { 22 | margin-right: 60px; 23 | } 24 | 25 | 26 | .chat li .chat-body p 27 | { 28 | margin: 0; 29 | color: #777777; 30 | } 31 | 32 | .panel .slidedown .glyphicon, .chat .glyphicon 33 | { 34 | margin-right: 5px; 35 | } 36 | 37 | .panel-body 38 | { 39 | overflow-y: scroll; 40 | height: 250px; 41 | } 42 | 43 | ::-webkit-scrollbar-track 44 | { 45 | -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3); 46 | background-color: #F5F5F5; 47 | } 48 | 49 | ::-webkit-scrollbar 50 | { 51 | width: 12px; 52 | background-color: #F5F5F5; 53 | } 54 | 55 | ::-webkit-scrollbar-thumb 56 | { 57 | -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3); 58 | background-color: #555; 59 | } 60 | -------------------------------------------------------------------------------- /src/app/chat/chat.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |
5 |
6 | {{ msgData.room }} 7 |
8 | 11 |
12 |
13 |
14 |
    15 |
  • 16 |
    17 | 18 | User Avatar 19 | 20 |
    21 |
    22 | {{ c.nickname }} 23 | {{ c.updated_at | date: 'medium' }} 24 |
    25 |

    {{ c.message }}

    26 |
    27 |
    28 | 29 |
    30 | 31 | User Avatar 32 | 33 |
    34 |
    35 | {{ c.updated_at | date: 'medium' }} 36 | {{ c.nickname }} 37 |
    38 |

    {{ c.message }}

    39 |
    40 |
    41 |
    42 |
  • 43 |
44 |
45 | 58 |
59 | 60 |
61 |
62 |

Select Chat Room

63 |
64 |
65 | 66 |
67 |
68 | 74 |
75 |
76 | 77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 | -------------------------------------------------------------------------------- /src/app/chat/chat.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { ChatComponent } from './chat.component'; 4 | 5 | describe('ChatComponent', () => { 6 | let component: ChatComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ ChatComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(ChatComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/app/chat/chat.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit, AfterViewChecked, ElementRef, ViewChild } from '@angular/core'; 2 | import { ChatService } from '../chat.service'; 3 | import * as io from "socket.io-client"; 4 | 5 | @Component({ 6 | selector: 'app-chat', 7 | templateUrl: './chat.component.html', 8 | styleUrls: ['./chat.component.css'] 9 | }) 10 | export class ChatComponent implements OnInit, AfterViewChecked { 11 | 12 | @ViewChild('scrollMe') private myScrollContainer: ElementRef; 13 | 14 | chats: any; 15 | joinned: boolean = false; 16 | newUser = { nickname: '', room: '' }; 17 | msgData = { room: '', nickname: '', message: '' }; 18 | socket = io('http://localhost:4000'); 19 | 20 | constructor(private chatService: ChatService) {} 21 | 22 | ngOnInit() { 23 | var user = JSON.parse(localStorage.getItem("user")); 24 | if(user!==null) { 25 | this.getChatByRoom(user.room); 26 | this.msgData = { room: user.room, nickname: user.nickname, message: '' } 27 | this.joinned = true; 28 | this.scrollToBottom(); 29 | } 30 | this.socket.on('new-message', function (data) { 31 | if(data.message.room === JSON.parse(localStorage.getItem("user")).room) { 32 | this.chats.push(data.message); 33 | this.msgData = { room: user.room, nickname: user.nickname, message: '' } 34 | this.scrollToBottom(); 35 | } 36 | }.bind(this)); 37 | } 38 | 39 | ngAfterViewChecked() { 40 | this.scrollToBottom(); 41 | } 42 | 43 | scrollToBottom(): void { 44 | try { 45 | this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight; 46 | } catch(err) { } 47 | } 48 | 49 | getChatByRoom(room) { 50 | this.chatService.getChatByRoom(room).then((res) => { 51 | this.chats = res; 52 | }, (err) => { 53 | console.log(err); 54 | }); 55 | } 56 | 57 | joinRoom() { 58 | var date = new Date(); 59 | localStorage.setItem("user", JSON.stringify(this.newUser)); 60 | this.getChatByRoom(this.newUser.room); 61 | this.msgData = { room: this.newUser.room, nickname: this.newUser.nickname, message: '' }; 62 | this.joinned = true; 63 | this.socket.emit('save-message', { room: this.newUser.room, nickname: this.newUser.nickname, message: 'Join this room', updated_at: date }); 64 | } 65 | 66 | sendMessage() { 67 | this.chatService.saveChat(this.msgData).then((result) => { 68 | this.socket.emit('save-message', result); 69 | }, (err) => { 70 | console.log(err); 71 | }); 72 | } 73 | 74 | logout() { 75 | var date = new Date(); 76 | var user = JSON.parse(localStorage.getItem("user")); 77 | this.socket.emit('save-message', { room: user.room, nickname: user.nickname, message: 'Left this room', updated_at: date }); 78 | localStorage.removeItem("user"); 79 | this.joinned = false; 80 | } 81 | 82 | } 83 | -------------------------------------------------------------------------------- /src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didinj/mean-angular4-chat-app/bbb053a022681cf00af802ea55ee38387867cc7b/src/assets/.gitkeep -------------------------------------------------------------------------------- /src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true 3 | }; 4 | -------------------------------------------------------------------------------- /src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // The file contents for the current environment will overwrite these during build. 2 | // The build system defaults to the dev environment which uses `environment.ts`, but if you do 3 | // `ng build --env=prod` then `environment.prod.ts` will be used instead. 4 | // The list of which env maps to which file can be found in `.angular-cli.json`. 5 | 6 | export const environment = { 7 | production: false 8 | }; 9 | -------------------------------------------------------------------------------- /src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didinj/mean-angular4-chat-app/bbb053a022681cf00af802ea55ee38387867cc7b/src/favicon.ico -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | MeanChat 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | Loading... 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/set'; 35 | 36 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 37 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 38 | 39 | /** IE10 and IE11 requires the following to support `@angular/animation`. */ 40 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 41 | 42 | 43 | /** Evergreen browsers require these. **/ 44 | import 'core-js/es6/reflect'; 45 | import 'core-js/es7/reflect'; 46 | 47 | 48 | /** ALL Firefox browsers require the following to support `@angular/animation`. **/ 49 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 50 | 51 | 52 | 53 | /*************************************************************************************************** 54 | * Zone JS is required by Angular itself. 55 | */ 56 | import 'zone.js/dist/zone'; // Included with Angular CLI. 57 | 58 | 59 | 60 | /*************************************************************************************************** 61 | * APPLICATION IMPORTS 62 | */ 63 | 64 | /** 65 | * Date, currency, decimal and percent pipes. 66 | * Needed for: All but Chrome, Firefox, Edge, IE11 and Safari 10 67 | */ 68 | // import 'intl'; // Run `npm install --save intl`. 69 | -------------------------------------------------------------------------------- /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/long-stack-trace-zone'; 4 | import 'zone.js/dist/proxy.js'; 5 | import 'zone.js/dist/sync-test'; 6 | import 'zone.js/dist/jasmine-patch'; 7 | import 'zone.js/dist/async-test'; 8 | import 'zone.js/dist/fake-async-test'; 9 | import { getTestBed } from '@angular/core/testing'; 10 | import { 11 | BrowserDynamicTestingModule, 12 | platformBrowserDynamicTesting 13 | } from '@angular/platform-browser-dynamic/testing'; 14 | 15 | // Unfortunately there's no typing for the `__karma__` variable. Just declare it as any. 16 | declare var __karma__: any; 17 | declare var require: any; 18 | 19 | // Prevent Karma from running prematurely. 20 | __karma__.loaded = function () {}; 21 | 22 | // First, initialize the Angular testing environment. 23 | getTestBed().initTestEnvironment( 24 | BrowserDynamicTestingModule, 25 | platformBrowserDynamicTesting() 26 | ); 27 | // Then we find all the tests. 28 | const context = require.context('./', true, /\.spec\.ts$/); 29 | // And load the modules. 30 | context.keys().map(context); 31 | // Finally, start Karma to run the tests. 32 | __karma__.start(); 33 | -------------------------------------------------------------------------------- /src/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "module": "es2015", 6 | "baseUrl": "", 7 | "types": [] 8 | }, 9 | "exclude": [ 10 | "test.ts", 11 | "**/*.spec.ts" 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /src/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/spec", 5 | "module": "commonjs", 6 | "target": "es5", 7 | "baseUrl": "", 8 | "types": [ 9 | "jasmine", 10 | "node" 11 | ] 12 | }, 13 | "files": [ 14 | "test.ts" 15 | ], 16 | "include": [ 17 | "**/*.spec.ts", 18 | "**/*.d.ts" 19 | ] 20 | } 21 | -------------------------------------------------------------------------------- /src/typings.d.ts: -------------------------------------------------------------------------------- 1 | /* SystemJS module definition */ 2 | declare var module: NodeModule; 3 | interface NodeModule { 4 | id: string; 5 | } 6 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "outDir": "./dist/out-tsc", 5 | "baseUrl": "src", 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 | "es2016", 17 | "dom" 18 | ] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "rulesDirectory": [ 3 | "node_modules/codelyzer" 4 | ], 5 | "rules": { 6 | "callable-types": true, 7 | "class-name": true, 8 | "comment-format": [ 9 | true, 10 | "check-space" 11 | ], 12 | "curly": true, 13 | "eofline": true, 14 | "forin": true, 15 | "import-blacklist": [true, "rxjs"], 16 | "import-spacing": true, 17 | "indent": [ 18 | true, 19 | "spaces" 20 | ], 21 | "interface-over-type-literal": true, 22 | "label-position": true, 23 | "max-line-length": [ 24 | true, 25 | 140 26 | ], 27 | "member-access": false, 28 | "member-ordering": [ 29 | true, 30 | "static-before-instance", 31 | "variables-before-functions" 32 | ], 33 | "no-arg": true, 34 | "no-bitwise": true, 35 | "no-console": [ 36 | true, 37 | "debug", 38 | "info", 39 | "time", 40 | "timeEnd", 41 | "trace" 42 | ], 43 | "no-construct": true, 44 | "no-debugger": true, 45 | "no-duplicate-variable": true, 46 | "no-empty": false, 47 | "no-empty-interface": true, 48 | "no-eval": true, 49 | "no-inferrable-types": [true, "ignore-params"], 50 | "no-shadowed-variable": true, 51 | "no-string-literal": false, 52 | "no-string-throw": true, 53 | "no-switch-case-fall-through": true, 54 | "no-trailing-whitespace": true, 55 | "no-unused-expression": true, 56 | "no-use-before-declare": true, 57 | "no-var-keyword": true, 58 | "object-literal-sort-keys": false, 59 | "one-line": [ 60 | true, 61 | "check-open-brace", 62 | "check-catch", 63 | "check-else", 64 | "check-whitespace" 65 | ], 66 | "prefer-const": true, 67 | "quotemark": [ 68 | true, 69 | "single" 70 | ], 71 | "radix": true, 72 | "semicolon": [ 73 | "always" 74 | ], 75 | "triple-equals": [ 76 | true, 77 | "allow-null-check" 78 | ], 79 | "typedef-whitespace": [ 80 | true, 81 | { 82 | "call-signature": "nospace", 83 | "index-signature": "nospace", 84 | "parameter": "nospace", 85 | "property-declaration": "nospace", 86 | "variable-declaration": "nospace" 87 | } 88 | ], 89 | "typeof-compare": true, 90 | "unified-signatures": true, 91 | "variable-name": false, 92 | "whitespace": [ 93 | true, 94 | "check-branch", 95 | "check-decl", 96 | "check-operator", 97 | "check-separator", 98 | "check-type" 99 | ], 100 | 101 | "directive-selector": [true, "attribute", "app", "camelCase"], 102 | "component-selector": [true, "element", "app", "kebab-case"], 103 | "use-input-property-decorator": true, 104 | "use-output-property-decorator": true, 105 | "use-host-property-decorator": true, 106 | "no-input-rename": true, 107 | "no-output-rename": true, 108 | "use-life-cycle-interface": true, 109 | "use-pipe-transform-interface": true, 110 | "component-class-suffix": true, 111 | "directive-class-suffix": true, 112 | "no-access-missing-member": true, 113 | "templates-use-public": true, 114 | "invoke-injectable": true 115 | } 116 | } 117 | --------------------------------------------------------------------------------