├── .editorconfig
├── .gitignore
├── README.md
├── angular.json
├── app.json
├── e2e
├── app.e2e-spec.ts
├── app.po.ts
└── tsconfig.e2e.json
├── karma.conf.js
├── package-lock.json
├── package.json
├── protractor.conf.js
├── server.js
├── src
├── app
│ ├── app.component.css
│ ├── app.component.html
│ ├── app.component.spec.ts
│ ├── app.component.ts
│ ├── app.module.ts
│ └── contacts
│ │ ├── contact-details
│ │ ├── contact-details.component.css
│ │ ├── contact-details.component.html
│ │ ├── contact-details.component.spec.ts
│ │ └── contact-details.component.ts
│ │ ├── contact-list
│ │ ├── contact-list.component.css
│ │ ├── contact-list.component.html
│ │ ├── contact-list.component.spec.ts
│ │ └── contact-list.component.ts
│ │ ├── contact.service.spec.ts
│ │ ├── contact.service.ts
│ │ └── contact.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
/.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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | # Mean Contactlist Angular2
3 |
4 | Contact List is a RESTful API server and web application built with the MEAN (Angular 2) stack. It is a simple example that aims to concisely demonstrate basic MEAN and REST architecture. You can find the full tutorial here: https://devcenter.heroku.com/articles/mean-apps-restful-api.
5 |
6 | You can deploy a live copy of this application to Heroku with the button below.
7 |
8 | [](https://heroku.com/deploy?template=https://github.com/chrisckchang/mean-contactlist-angular2)
9 |
--------------------------------------------------------------------------------
/angular.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
3 | "version": 1,
4 | "newProjectRoot": "projects",
5 | "projects": {
6 | "mean-contactlist-angular2": {
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/mean-contactlist-angular2",
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": "mean-contactlist-angular2:build"
54 | },
55 | "configurations": {
56 | "production": {
57 | "browserTarget": "mean-contactlist-angular2:build:production"
58 | }
59 | }
60 | },
61 | "extract-i18n": {
62 | "builder": "@angular-devkit/build-angular:extract-i18n",
63 | "options": {
64 | "browserTarget": "mean-contactlist-angular2: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 | "mean-contactlist-angular2-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": "mean-contactlist-angular2:serve"
107 | },
108 | "configurations": {
109 | "production": {
110 | "devServerTarget": "mean-contactlist-angular2: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": "mean-contactlist-angular2"
127 | }
--------------------------------------------------------------------------------
/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "MEAN Contact List",
3 | "description": "Example contact list app using MEAN",
4 | "keywords": [
5 | "MEAN",
6 | "Angular",
7 | "Node",
8 | "MongoDB",
9 | "mLab"
10 | ],
11 | "repository": "https://github.com/chrisckchang/mean-contactlist-angular2",
12 | "success_url": "/",
13 | "formation": {
14 | "web": {
15 | "quantity": 1,
16 | "size": "free"
17 | }
18 | },
19 | "addons": [
20 | "mongolab"
21 | ]
22 | }
23 |
--------------------------------------------------------------------------------
/e2e/app.e2e-spec.ts:
--------------------------------------------------------------------------------
1 | import { MeanContactlistAngular2Page } from './app.po';
2 |
3 | describe('mean-contactlist-angular2 App', () => {
4 | let page: MeanContactlistAngular2Page;
5 |
6 | beforeEach(() => {
7 | page = new MeanContactlistAngular2Page();
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 MeanContactlistAngular2Page {
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 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "mean-contactlist-angular2",
3 | "version": "0.0.0",
4 | "license": "MIT",
5 | "scripts": {
6 | "ng": "ng",
7 | "start": "node server.js",
8 | "build": "ng build",
9 | "test": "ng test",
10 | "lint": "ng lint",
11 | "e2e": "ng e2e",
12 | "postinstall": "ng build --output-path dist"
13 | },
14 | "private": true,
15 | "dependencies": {
16 | "@angular/animations": "^6.0.3",
17 | "@angular/cli": "^6.0.8",
18 | "@angular/common": "^6.0.3",
19 | "@angular/compiler": "^6.0.3",
20 | "@angular/compiler-cli": "^6.0.7",
21 | "@angular/core": "^6.0.3",
22 | "@angular/forms": "^6.0.3",
23 | "@angular/http": "^6.0.3",
24 | "@angular/platform-browser": "^6.0.3",
25 | "@angular/platform-browser-dynamic": "^6.0.3",
26 | "@angular/router": "^6.0.3",
27 | "body-parser": "^1.18.3",
28 | "core-js": "^2.5.4",
29 | "express": "^4.16.3",
30 | "mongodb": "^3.1.1",
31 | "rxjs": "^6.0.0",
32 | "zone.js": "^0.8.26"
33 | },
34 | "devDependencies": {
35 | "@angular-devkit/build-angular": "~0.6.8",
36 | "@angular/language-service": "^6.0.3",
37 | "@types/jasmine": "~2.8.6",
38 | "@types/jasminewd2": "~2.0.3",
39 | "@types/node": "~8.9.4",
40 | "codelyzer": "~4.2.1",
41 | "jasmine-core": "~2.99.1",
42 | "jasmine-spec-reporter": "~4.2.1",
43 | "karma": "~1.7.1",
44 | "karma-chrome-launcher": "~2.2.0",
45 | "karma-coverage-istanbul-reporter": "~2.0.0",
46 | "karma-jasmine": "~1.1.1",
47 | "karma-jasmine-html-reporter": "^0.2.2",
48 | "protractor": "~5.3.0",
49 | "ts-node": "~5.0.1",
50 | "tslint": "~5.9.1",
51 | "typescript": "~2.7.2"
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 |
--------------------------------------------------------------------------------
/server.js:
--------------------------------------------------------------------------------
1 | var express = require("express");
2 | var bodyParser = require("body-parser");
3 | var mongodb = require("mongodb");
4 | var ObjectID = mongodb.ObjectID;
5 |
6 | var CONTACTS_COLLECTION = "contacts";
7 |
8 | var app = express();
9 | app.use(bodyParser.json());
10 |
11 | // Create link to Angular build directory
12 | var distDir = __dirname + "/dist/";
13 | app.use(express.static(distDir));
14 |
15 | // Create a database variable outside of the database connection callback to reuse the connection pool in your app.
16 | var db;
17 |
18 | // Connect to the database before starting the application server.
19 | mongodb.MongoClient.connect(process.env.MONGODB_URI || "mongodb://localhost:27017/test", function (err, client) {
20 | if (err) {
21 | console.log(err);
22 | process.exit(1);
23 | }
24 |
25 | // Save database object from the callback for reuse.
26 | db = client.db();
27 | console.log("Database connection ready");
28 |
29 | // Initialize the app.
30 | var server = app.listen(process.env.PORT || 8080, function () {
31 | var port = server.address().port;
32 | console.log("App now running on port", port);
33 | });
34 | });
35 |
36 | // CONTACTS API ROUTES BELOW
37 |
38 | // Generic error handler used by all endpoints.
39 | function handleError(res, reason, message, code) {
40 | console.log("ERROR: " + reason);
41 | res.status(code || 500).json({"error": message});
42 | }
43 |
44 | /* "/api/contacts"
45 | * GET: finds all contacts
46 | * POST: creates a new contact
47 | */
48 |
49 | app.get("/api/contacts", function(req, res) {
50 | db.collection(CONTACTS_COLLECTION).find({}).toArray(function(err, docs) {
51 | if (err) {
52 | handleError(res, err.message, "Failed to get contacts.");
53 | } else {
54 | res.status(200).json(docs);
55 | }
56 | });
57 | });
58 |
59 | app.post("/api/contacts", function(req, res) {
60 | var newContact = req.body;
61 | newContact.createDate = new Date();
62 |
63 | if (!req.body.name) {
64 | handleError(res, "Invalid user input", "Must provide a name.", 400);
65 | } else {
66 | db.collection(CONTACTS_COLLECTION).insertOne(newContact, function(err, doc) {
67 | if (err) {
68 | handleError(res, err.message, "Failed to create new contact.");
69 | } else {
70 | res.status(201).json(doc.ops[0]);
71 | }
72 | });
73 | }
74 | });
75 |
76 | /* "/api/contacts/:id"
77 | * GET: find contact by id
78 | * PUT: update contact by id
79 | * DELETE: deletes contact by id
80 | */
81 |
82 | app.get("/api/contacts/:id", function(req, res) {
83 | db.collection(CONTACTS_COLLECTION).findOne({ _id: new ObjectID(req.params.id) }, function(err, doc) {
84 | if (err) {
85 | handleError(res, err.message, "Failed to get contact");
86 | } else {
87 | res.status(200).json(doc);
88 | }
89 | });
90 | });
91 |
92 | app.put("/api/contacts/:id", function(req, res) {
93 | var updateDoc = req.body;
94 | delete updateDoc._id;
95 |
96 | db.collection(CONTACTS_COLLECTION).updateOne({_id: new ObjectID(req.params.id)}, updateDoc, function(err, doc) {
97 | if (err) {
98 | handleError(res, err.message, "Failed to update contact");
99 | } else {
100 | updateDoc._id = req.params.id;
101 | res.status(200).json(updateDoc);
102 | }
103 | });
104 | });
105 |
106 | app.delete("/api/contacts/:id", function(req, res) {
107 | db.collection(CONTACTS_COLLECTION).deleteOne({_id: new ObjectID(req.params.id)}, function(err, result) {
108 | if (err) {
109 | handleError(res, err.message, "Failed to delete contact");
110 | } else {
111 | res.status(200).json(req.params.id);
112 | }
113 | });
114 | });
115 |
--------------------------------------------------------------------------------
/src/app/app.component.css:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chrisckchang/mean-contactlist-angular2/6643c61338750610decd41d2ba16f041be734cc1/src/app/app.component.css
--------------------------------------------------------------------------------
/src/app/app.component.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/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 |
6 | import { AppComponent } from './app.component';
7 | import { ContactDetailsComponent } from './contacts/contact-details/contact-details.component';
8 | import { ContactListComponent } from './contacts/contact-list/contact-list.component';
9 |
10 | @NgModule({
11 | declarations: [
12 | AppComponent,
13 | ContactDetailsComponent,
14 | ContactListComponent
15 | ],
16 | imports: [
17 | BrowserModule,
18 | FormsModule,
19 | HttpModule
20 | ],
21 | providers: [],
22 | bootstrap: [AppComponent]
23 | })
24 | export class AppModule { }
25 |
--------------------------------------------------------------------------------
/src/app/contacts/contact-details/contact-details.component.css:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chrisckchang/mean-contactlist-angular2/6643c61338750610decd41d2ba16f041be734cc1/src/app/contacts/contact-details/contact-details.component.css
--------------------------------------------------------------------------------
/src/app/contacts/contact-details/contact-details.component.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
Contact Details
4 | New Contact
5 |
6 |
7 |
--------------------------------------------------------------------------------
/src/app/contacts/contact-details/contact-details.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
2 |
3 | import { ContactDetailsComponent } from './contact-details.component';
4 |
5 | describe('ContactDetailsComponent', () => {
6 | let component: ContactDetailsComponent;
7 | let fixture: ComponentFixture;
8 |
9 | beforeEach(async(() => {
10 | TestBed.configureTestingModule({
11 | declarations: [ ContactDetailsComponent ]
12 | })
13 | .compileComponents();
14 | }));
15 |
16 | beforeEach(() => {
17 | fixture = TestBed.createComponent(ContactDetailsComponent);
18 | component = fixture.componentInstance;
19 | fixture.detectChanges();
20 | });
21 |
22 | it('should create', () => {
23 | expect(component).toBeTruthy();
24 | });
25 | });
26 |
--------------------------------------------------------------------------------
/src/app/contacts/contact-details/contact-details.component.ts:
--------------------------------------------------------------------------------
1 | import { Component, Input } from '@angular/core';
2 | import { Contact } from '../contact';
3 | import { ContactService } from '../contact.service';
4 |
5 | @Component({
6 | selector: 'contact-details',
7 | templateUrl: './contact-details.component.html',
8 | styleUrls: ['./contact-details.component.css']
9 | })
10 |
11 | export class ContactDetailsComponent {
12 | @Input()
13 | contact: Contact;
14 |
15 | @Input()
16 | createHandler: Function;
17 | @Input()
18 | updateHandler: Function;
19 | @Input()
20 | deleteHandler: Function;
21 |
22 | constructor (private contactService: ContactService) {}
23 |
24 | createContact(contact: Contact) {
25 | this.contactService.createContact(contact).then((newContact: Contact) => {
26 | this.createHandler(newContact);
27 | });
28 | }
29 |
30 | updateContact(contact: Contact): void {
31 | this.contactService.updateContact(contact).then((updatedContact: Contact) => {
32 | this.updateHandler(updatedContact);
33 | });
34 | }
35 |
36 | deleteContact(contactId: String): void {
37 | this.contactService.deleteContact(contactId).then((deletedContactId: String) => {
38 | this.deleteHandler(deletedContactId);
39 | });
40 | }
41 | }
--------------------------------------------------------------------------------
/src/app/contacts/contact-list/contact-list.component.css:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chrisckchang/mean-contactlist-angular2/6643c61338750610decd41d2ba16f041be734cc1/src/app/contacts/contact-list/contact-list.component.css
--------------------------------------------------------------------------------
/src/app/contacts/contact-list/contact-list.component.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
Contacts
4 |
5 | -
9 | {{contact.name}}
10 |
11 |
12 |
13 |
14 |
15 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/src/app/contacts/contact-list/contact-list.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
2 |
3 | import { ContactListComponent } from './contact-list.component';
4 |
5 | describe('ContactListComponent', () => {
6 | let component: ContactListComponent;
7 | let fixture: ComponentFixture;
8 |
9 | beforeEach(async(() => {
10 | TestBed.configureTestingModule({
11 | declarations: [ ContactListComponent ]
12 | })
13 | .compileComponents();
14 | }));
15 |
16 | beforeEach(() => {
17 | fixture = TestBed.createComponent(ContactListComponent);
18 | component = fixture.componentInstance;
19 | fixture.detectChanges();
20 | });
21 |
22 | it('should create', () => {
23 | expect(component).toBeTruthy();
24 | });
25 | });
26 |
--------------------------------------------------------------------------------
/src/app/contacts/contact-list/contact-list.component.ts:
--------------------------------------------------------------------------------
1 | import { Component, OnInit } from '@angular/core';
2 | import { Contact } from '../contact';
3 | import { ContactService } from '../contact.service';
4 | import { ContactDetailsComponent } from '../contact-details/contact-details.component';
5 |
6 | @Component({
7 | selector: 'contact-list',
8 | templateUrl: './contact-list.component.html',
9 | styleUrls: ['./contact-list.component.css'],
10 | providers: [ContactService]
11 | })
12 |
13 | export class ContactListComponent implements OnInit {
14 |
15 | contacts: Contact[]
16 | selectedContact: Contact
17 |
18 | constructor(private contactService: ContactService) { }
19 |
20 | ngOnInit() {
21 | this.contactService
22 | .getContacts()
23 | .then((contacts: Contact[]) => {
24 | this.contacts = contacts.map((contact) => {
25 | if (!contact.phone) {
26 | contact.phone = {
27 | mobile: '',
28 | work: ''
29 | }
30 | }
31 | return contact;
32 | });
33 | });
34 | }
35 |
36 | private getIndexOfContact = (contactId: String) => {
37 | return this.contacts.findIndex((contact) => {
38 | return contact._id === contactId;
39 | });
40 | }
41 |
42 | selectContact(contact: Contact) {
43 | this.selectedContact = contact
44 | }
45 |
46 | createNewContact() {
47 | var contact: Contact = {
48 | name: '',
49 | email: '',
50 | phone: {
51 | work: '',
52 | mobile: ''
53 | }
54 | };
55 |
56 | // By default, a newly-created contact will have the selected state.
57 | this.selectContact(contact);
58 | }
59 |
60 | deleteContact = (contactId: String) => {
61 | var idx = this.getIndexOfContact(contactId);
62 | if (idx !== -1) {
63 | this.contacts.splice(idx, 1);
64 | this.selectContact(null);
65 | }
66 | return this.contacts;
67 | }
68 |
69 | addContact = (contact: Contact) => {
70 | this.contacts.push(contact);
71 | this.selectContact(contact);
72 | return this.contacts;
73 | }
74 |
75 | updateContact = (contact: Contact) => {
76 | var idx = this.getIndexOfContact(contact._id);
77 | if (idx !== -1) {
78 | this.contacts[idx] = contact;
79 | this.selectContact(contact);
80 | }
81 | return this.contacts;
82 | }
83 | }
--------------------------------------------------------------------------------
/src/app/contacts/contact.service.spec.ts:
--------------------------------------------------------------------------------
1 | import { TestBed, inject } from '@angular/core/testing';
2 |
3 | import { ContactService } from './contact.service';
4 |
5 | describe('ContactService', () => {
6 | beforeEach(() => {
7 | TestBed.configureTestingModule({
8 | providers: [ContactService]
9 | });
10 | });
11 |
12 | it('should ...', inject([ContactService], (service: ContactService) => {
13 | expect(service).toBeTruthy();
14 | }));
15 | });
16 |
--------------------------------------------------------------------------------
/src/app/contacts/contact.service.ts:
--------------------------------------------------------------------------------
1 | import { Injectable } from '@angular/core';
2 | import { Contact } from './contact';
3 | import { Http, Response } from '@angular/http';
4 |
5 | @Injectable()
6 | export class ContactService {
7 | private contactsUrl = '/api/contacts';
8 |
9 | constructor (private http: Http) {}
10 |
11 | // get("/api/contacts")
12 | getContacts(): Promise {
13 | return this.http.get(this.contactsUrl)
14 | .toPromise()
15 | .then(response => response.json() as Contact[])
16 | .catch(this.handleError);
17 | }
18 |
19 | // post("/api/contacts")
20 | createContact(newContact: Contact): Promise {
21 | return this.http.post(this.contactsUrl, newContact)
22 | .toPromise()
23 | .then(response => response.json() as Contact)
24 | .catch(this.handleError);
25 | }
26 |
27 | // get("/api/contacts/:id") endpoint not used by Angular app
28 |
29 | // delete("/api/contacts/:id")
30 | deleteContact(delContactId: String): Promise {
31 | return this.http.delete(this.contactsUrl + '/' + delContactId)
32 | .toPromise()
33 | .then(response => response.json() as String)
34 | .catch(this.handleError);
35 | }
36 |
37 | // put("/api/contacts/:id")
38 | updateContact(putContact: Contact): Promise {
39 | var putUrl = this.contactsUrl + '/' + putContact._id;
40 | return this.http.put(putUrl, putContact)
41 | .toPromise()
42 | .then(response => response.json() as Contact)
43 | .catch(this.handleError);
44 | }
45 |
46 | private handleError (error: any): Promise {
47 | let errMsg = (error.message) ? error.message :
48 | error.status ? `${error.status} - ${error.statusText}` : 'Server error';
49 | console.error(errMsg); // log to console
50 | return Promise.reject(errMsg);
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/app/contacts/contact.ts:
--------------------------------------------------------------------------------
1 | export class Contact {
2 | _id?: string;
3 | name: string;
4 | email: string;
5 | phone: {
6 | mobile: string;
7 | work: string;
8 | }
9 | }
--------------------------------------------------------------------------------
/src/assets/.gitkeep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chrisckchang/mean-contactlist-angular2/6643c61338750610decd41d2ba16f041be734cc1/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/chrisckchang/mean-contactlist-angular2/6643c61338750610decd41d2ba16f041be734cc1/src/favicon.ico
--------------------------------------------------------------------------------
/src/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | MeanContactlistAngular2
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 | Loading...
17 |
18 |
19 |
--------------------------------------------------------------------------------
/src/main.ts:
--------------------------------------------------------------------------------
1 | import './polyfills.ts';
2 | import { enableProdMode } from '@angular/core';
3 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
4 |
5 | import { AppModule } from './app/app.module';
6 | import { environment } from './environments/environment';
7 |
8 | if (environment.production) {
9 | enableProdMode();
10 | }
11 |
12 | platformBrowserDynamic().bootstrapModule(AppModule)
13 | .catch(err => console.log(err));
14 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------