Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Connect the Angular App to the MongoDB Database #219

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
394 changes: 286 additions & 108 deletions package-lock.json

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,17 @@
"@angular/platform-browser": "^6.0.0-rc.1",
"@angular/platform-browser-dynamic": "^6.0.0-rc.1",
"@angular/router": "^6.0.0-rc.1",
"body-parser": "^1.18.3",
"chart.js": "^2.5.0",
"classlist.js": "^1.1.20150312",
"core-js": "^2.4.1",
"express": "^4.16.3",
"font-awesome": "^4.7.0",
"hammerjs": "^2.0.8",
"mongoose": "^5.1.6",
"rxjs": "^6.0.0-rc.1",
"rxjs-compat": "^6.0.0-rc.1",
"save": "^2.3.2",
"web-animations-js": "^2.3.1",
"zone.js": "^0.8.19"
},
Expand Down
93 changes: 93 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
var express = require('express');
var path = require("path");
var bodyParser = require('body-parser');
var mongo = require("mongoose");

var db = mongo.connect("mongodb://localhost:27017/AngularCRUD", function(err, response){
if(err){ console.log( err); }
else{ console.log('Connected to ' + db, ' + ', response); }
});


var app = express()
app.use(bodyParser());
app.use(bodyParser.json({limit:'5mb'}));
app.use(bodyParser.urlencoded({extended:true}));


app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});

var Schema = mongo.Schema;

var UsersSchema = new Schema({
name: { type: String },
address: { type: String },
},{ versionKey: false });


var model = mongo.model('users', UsersSchema, 'users');

app.post("/api/SaveUser",function(req,res){
var mod = new model(req.body);
if(req.body.mode =="Save")
{
mod.save(function(err,data){
if(err){
res.send(err);
}
else{
res.send({data:"Record has been Inserted..!!"});
}
});
}
else
{
model.findByIdAndUpdate(req.body.id, { name: req.body.name, address: req.body.address},
function(err,data) {
if (err) {
res.send(err);
}
else{
res.send({data:"Record has been Updated..!!"});
}
});


}
})

app.post("/api/deleteUser",function(req,res){
model.remove({ _id: req.body.id }, function(err) {
if(err){
res.send(err);
}
else{
res.send({data:"Record has been Deleted..!!"});
}
});
})



app.get("/api/getUser",function(req,res){
model.find({},function(err,data){
if(err){
res.send(err);
}
else{
res.send(data);
}
});
})


app.listen(8080, function () {

console.log('Example app listening on port 8080!')
})
2 changes: 1 addition & 1 deletion src/app/app.component.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
<app-navbar></app-navbar>
<router-outlet></router-outlet>
<app-footer></app-footer>
<app-footer></app-footer>
45 changes: 40 additions & 5 deletions src/app/app.component.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,45 @@
import { Component } from "@angular/core";
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators, FormsModule } from '@angular/forms';
import { CommonService } from './common.service';
import { Http, Response, Headers, RequestOptions } from '@angular/http';

@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.scss"]
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = "app";
title = 'app';
constructor(private newService: CommonService, ) { }
Repdata;
valbutton = 'Save';


ngOnInit() {
this.newService.GetUser().subscribe(data => this.Repdata = data);
}

onSave = function (user, isValid: boolean) {
user.mode = this.valbutton;
this.newService.saveUser(user)
.subscribe(data => {
alert(data.data);

this.ngOnInit();
}
, error => this.errorMessage = error);

};
edit = function (kk) {
this.id = kk._id;
this.name = kk.name;
this.address = kk.address;
this.valbutton = 'Update';
};

delete = function (id) {
this.newService.deleteUser(id)
.subscribe(data => { alert(data.data); this.ngOnInit(); }, error => this.errorMessage = error);
};

}
6 changes: 4 additions & 2 deletions src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import {CommonService} from './common.service';
import { HttpModule } from '@angular/http';
import { AgmCoreModule } from '@agm/core';
import { MDBBootstrapModule } from './typescripts/free';
import { FormsModule } from '@angular/forms';
Expand All @@ -29,13 +30,14 @@ import { ContactComponent } from './contact/contact.component';
BrowserAnimationsModule,
MDBBootstrapModule.forRoot(),
FormsModule,
HttpModule,
AppRoutingModule,
AgmCoreModule.forRoot({
// https://developers.google.com/maps/documentation/javascript/get-api-key?hl=en#key
apiKey: 'Your_api_key'
})
],
providers: [],
providers: [ CommonService ],
bootstrap: [AppComponent],
schemas: [ NO_ERRORS_SCHEMA ]
})
Expand Down
15 changes: 15 additions & 0 deletions src/app/common.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { TestBed, inject } from '@angular/core/testing';

import { CommonService } from './common.service';

describe('CommonService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [CommonService]
});
});

it('should be created', inject([CommonService], (service: CommonService) => {
expect(service).toBeTruthy();
}));
});
27 changes: 27 additions & 0 deletions src/app/common.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';

@Injectable()
export class CommonService {

constructor(private http: Http) { }

saveUser(user) {
return this.http.post('http://localhost:8080/api/SaveUser/', user)
.map((response: Response) => response.json())
}

GetUser() {
return this.http.get('http://localhost:8080/api/getUser/')
.map((response: Response) => response.json())
}
deleteUser(id) {
return this.http.post('http://localhost:8080/api/deleteUser/', { 'id': id })
.map((response: Response) => response.json())
}

}