follow me on facebook

Sunday 9 February 2020

Crud operations using database and services



app.module.ts
----------------------
import {FormsModulefrom '@angular/forms';
import {HttpClientModulefrom '@angular/common/http';


imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    HttpClientModule
  ],



Admin notifications.html
---------------------------------

<div class="container mt-3">
    
    <input type="text" name="searchTerm" placeholder="Search here.." [(ngModel)]="searchTerm">
    
  <button type="button" data-toggle="modal" data-target="#y" class="btn btn-info mx-auto d-block mt-2 mb-3">Add New Notifications</button>
  <!-- <div class="jumbotron"> -->
  
    <table class="table table-hover  table-secondary">
        <thead class="thead-dark">
          <th>sno</th>
          <th>Notification</th>
          <th>Posted On</th>
          </thead>
        <tr *ngFor="let i of arr; let a=index">
          <td>{{a +1}}</td>
          <td>{{i.notification}}</td>
          <td>{{i.date}}</td>
          <button (click)="edit(i)" data-target="#m" data-toggle="modal" class="btn btn-warning btn-sm">Edit</button>&nbsp;
           <button (click)="delete(i)"class="btn btn-danger btn-sm">X</button>
          </tr>
        </table>
        
        
  
  <div class="modal fade" id="y">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">Write here
            <button type="button" class="close" data-dismiss="modal">X</button>
          </div>
          <div class="modal-body">
              <form #ref="ngForm" (ngSubmit)="addData(ref.value)">
                  <div class="form-group">
                      <label for="notes1">Notification:</label>
                      <input type="text" name="notification" id="notes1" class="form-control" [(ngModel)]="notification">
                      <label for="date1">Date:</label>
                      <input type="date" name="date" id="date1" class="form-control" [(ngModel)]="date">
                    </div>
                    <button type="submit" class="btn btn-warning">Submit</button>
                </form>
          </div>
      </div>
    </div>
  </div>
  <!-- </div> -->
  <!-- ================================================ -->
  <div class="modal fade" id="m">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">Write here
            <button type="button" class="close" data-dismiss="modal">X</button>
          </div>
          <div class="modal-body">
              <form #ref1="ngForm" (ngSubmit)="update(ref1.value)">
                  <div class="form-group">
                      <label for="notes">Notification:</label>
                      <input type="text" name="notification" id="notes" class="form-control" [(ngModel)]=arr2.notification>
                      <label for="date">Date:</label>
                      <input type="date" name="date" id="date" class="form-control" [(ngModel)]=arr2.date>
                    </div>
                    <button type="submit"data-dismiss="modal" class="btn btn-warning" >update</button>
                </form>
          </div>
      </div>
    </div>
  </div>
  
  </div>


  


Admin notifications.ts
----------------------------------
import { ComponentOnInit } from '@angular/core';
import { NotificationsService } from '../notifications.service';

@Component({
  selector: 'app-adminnotifications',
  templateUrl: './adminnotifications.component.html',
  styleUrls: ['./adminnotifications.component.css']
})
export class AdminnotificationsComponent implements OnInit {
  

  constructor(private ns:NotificationsService) { }

  ngOnInit() {
    this.get()
  }

  arr:any;
  arr2:object[]=[];
  
  
addData(v)
{
this.ns.addNotification(v).subscribe(data=>{console.log(data)})
}

get()
{
  this.ns.getNotification().subscribe(temp=>{
   this.arr=temp})
}


edit(i) {
  this.arr2=i;
}

update()
{
  this.ns.updateNotification(this.arr2).subscribe(temp=>{
    this.get()
  })
}

delete(i) {
  this.ns.deleteNotification(i._id).subscribe(temp=>{
    this.get()
  })
}


}



NotificationsService.ts
----------------------------------
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class NotificationsService {

  constructor(private http:HttpClient) { }

  addNotification(data):Observable<any>
  {
    return this.http.post('http://localhost:3000/api/v1/admin/addnotification',data).pipe(response =>{return response})
    
  }

  getNotification():Observable<any>
  {
    return this.http.get('http://localhost:3000/api/v1/admin/notification');
    
  }

  updateNotification(data):Observable<any>
  {
    return this.http.put('http://localhost:3000/api/v1/admin/editnotification',data);
  }

  deleteNotification(id):Observable<any>
  {
    return this.http.delete(`http://localhost:3000/api/v1/admin/deletenotification/${id}`);
  }

  getStudentNotification():Observable<any>
  {
    return this.http.get('http://localhost:3000/api/v1/student/notification');
  }


}




Student notifications.html
----------------------------------
<div class="container mt-3">
    <input type="text" name="searchTerm" placeholder="Search.." [(ngModel)]="searchTerm">
  
    <h2>Notifications</h2>
    <table class="table table-secondary">
    <thead class="thead-dark">
      <th>Notification</th>
      <th>Date</th>
    </thead>
    <tr *ngFor="let i of arr ">
      <td>{{i.notification}}</td>
      <td>{{i.date}}</td>
      
    </tr>
  </table>
  
  
</div>



Student notifications.ts
--------------------------------
import { ComponentOnInit } from '@angular/core';
import { NotificationsService } from '../notifications.service';

@Component({
  selector: 'app-studentnotifications',
  templateUrl: './studentnotifications.component.html',
  styleUrls: ['./studentnotifications.component.css']
})
export class StudentnotificationsComponent implements OnInit {

  constructor(private ns:NotificationsService) { }

  ngOnInit() {
    this.get()
  }

  arr:any=[];
  notification:any;
  date:any;

  get()
  {
    this.ns.getStudentNotification().subscribe(temp=>{
     this.arr=temp})
  }


}


------------------------------------------------------BACKEND------------------------------------------------------

package.json
------------------
"dependencies": {
    "body-parser""^1.19.0",
    "cors""^2.8.5",
    "dotenv""^8.2.0",
    "express""^4.17.1",
    "mongodb""^3.5.2",
    "mongoose""^5.8.11",
    "path""^0.12.7"
  }


.env
-------------
MONGO_URI=mongodb+srv://mahesh:<password>@collegenoticeboard-xhb2c.mongodb.net/test?retryWrites=true&w=majority
PORT=3000



models/notifications.js
--------------------------------
const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const notificationsSchema = new mongoose.Schema({

    notification: {
        type:String,
        required:true
    },

    date:{
        type:String,
        required:true
    }
    
}, {versionKey: falsetimestamps: true});

module.exports=mongoose.model("notifications",notificationsSchema);


controllers/adminNotifications.js
------------------------------------------
const Notification = require("../models/notifications");

exports.createNotification = (reqres=> {
  const notification = new Notification(req.body);

  notification.save().then(result => {
    res.json({
      message: "notification added",
      status: 200,
      data: result
    });
  });
};

exports.getNotification = (reqres=> {
    Notification.find({}).then(result => {
      res.json(result);
    });
  };

exports.updateNotification =(req,res)=>{
    console.log(req.body)
    Notification.findOne({_id:req.body._id}).then((result)=>{
        if(result){
            Notification.update({_id:req.body._id},req.body).then((success)=>{
                res.json(success);
            }).catch((err)=>{res.json(err)})
        }
    }).catch((err)=>res.json(err))
}


exports.deleteNotification =(req,res)=>{
    Notification.find({_id:req.params.id}).then((result)=>{
        Notification.deleteOne({_id:req.params.id}).then((success)=>{
            res.json(success)
        })
    }).catch((err)=>res.json(err))
}



controllers/studentNotifications.js
------------------------------------------

const Notification = require("../models/notifications");

exports.getNotification = (reqres=> {
    Notification.find({}).then(result => {
      res.json(result);
    });
  };



routes/adminNotifications.js
------------------------------------
const express = require("express");
 const router = express.Router();

 const {createNotification,getNotification,updateNotification,deleteNotification} = require('../controllers/adminNotifications');


 //routes

router.post('/addnotification',createNotification);
router.get('/notification',getNotification);
router.put('/editnotification',updateNotification);
router.delete('/deletenotification/:id',deleteNotification);


module.exports = router;


routes/studentNotifications.js
------------------------------------

const express = require("express");
const router = express.Router();

 const {getNotification} = require('../controllers/studentNotifications');


 //routes
router.get('/notification',getNotification);



module.exports = router;




app.js
------------

const express = require('express');
const app = express();


var cors = require('cors');
const mongoose =require("mongoose");
const bodyParser =require("body-parser");

const dotenv = require('dotenv');
dotenv.config()

// ----------------mongodb start---------------------------------
mongoose.connect(
    process.env.MONGO_URI,
    { useNewUrlParser: trueuseUnifiedTopology: true }
 )
 .then(() => console.log('DB Connected'))
  mongoose.connection.on('error'err => {
     console.log(`DB connection error: ${err.message}`)
  });
 // -----------------mongodb end------------------------------------

//middleware
app.use(bodyParser.json());
app.use(cors());

//routes
app.use('/api/v1/admin',require('./routes/adminNotifications'));
app.use('/api/v1/student',require('./routes/studentNotifications'));

//port
const port = process.env.PORT || 3000;
app.listen(port, ()=> {console.log(`server listening on port: ${port}`)});










































































































Friday 7 February 2020

post (insert) operation using database


Insert data into table and perform crud operations without database

.html file
-------------------

<div class="container mt-3">
    
    <input type="text" name="searchingTerm" placeholder="Search here.." [(ngModel)]="searchingTerm">
    
<button type="button" data-toggle="modal" data-target="#y" class="btn btn-info mx-auto d-block mt-2 mb-3">Add Results</button>
<!-- <div class="jumbotron"> -->
    <table class="table table-hover table-secondary">
        <thead class="thead-dark">
          <th>sno</th>
          <th>Name</th>
          <th>English</th>
          <th>Physics</th>
          <th>Chemistry</th>
          <th>Engg drawing</th>
          <th>Maths</th>
        </thead>
        <tr *ngFor="let i of data; let a=index">
          <td>{{a + 1}}</td>
          <td>{{i.sname}}</td>
          <td>{{i.english}}</td>
          <td>{{i.physics}}</td> 
          <td>{{i.chemistry}}</td>
          <td>{{i.enggdrawing}}</td>
          <td>{{i.maths}}</td> 
          <button (click)="edit(i,a)" data-target="#m" data-toggle="modal" class="btn btn-warning btn-sm">Edit</button>&nbsp;
          <button (click)="delete(i)"class="btn btn-danger btn-sm">X</button>
        </tr>
        </table>
        
        
<!-- </div> -->
<div class="modal fade" id="y">
  <div class="modal-dialog">
    <div class="modal-content">
    <div class="modal-header"> <h2>Enter marks here</h2>
      <button type="button" class="close" data-dismiss="modal">X</button>
    </div>
    <div class="modal-body">
      <form #ref="ngForm" (ngSubmit)="addResults(ref.value)">
          <div class="form-group">

          <label for="stdname1">studentname:</label>
          <input type="text" name="sname" id="stdname1" class="form-control" [(ngModel)]=sname>
          <label for="english1">English:</label>
          <input type="text" name="english" id="english1" class="form-control" [(ngModel)]=english>
          <label for="physics1">Physics:</label>
          <input type="text" name="physics" id="physics1" class="form-control" [(ngModel)]=physics>
          <label for="chemistry1">Chemistry:</label>
          <input type="text" name="chemistry" id="chemistry1" class="form-control" [(ngModel)]=chemistry>
          <label for="enggdrawing1">Engg Drawing:</label>
          <input type="text" name="enggdrawing" id="enggdrawing1" class="form-control" [(ngModel)]=enggdrawing>
          <label for="math1">Maths:</label>
          <input type="text" name="maths" id="math1" class="form-control" [(ngModel)]=maths>
          
          </div>
          <button type="submit" class="btn btn-warning" >Submit</button>
      </form>
    </div>
  </div>
  </div>
</div>
<!-- =================================== -->
<div class="modal fade" id="m">
  <div class="modal-dialog"> 
    <div class="modal-content">
    <div class="modal-header"> <h2>Enter marks here</h2>
      <button type="button" class="close" data-dismiss="modal">X</button>
    </div>
    <div class="modal-body">
    <form #ref2="ngForm" (ngSubmit)="update(ref2.value)">
        <div class="form-group">

            <label for="stdname2">studentname:</label>
            <input type="text" name="sname" id="stdname2" class="form-control" [(ngModel)]=sname>
            <label for="english2">English:</label>
            <input type="text" name="english" id="english2" class="form-control" [(ngModel)]=english>
            <label for="physics2">Physics:</label>
            <input type="text" name="physics" id="physics2" class="form-control" [(ngModel)]=physics>
            <label for="chemistry2">Chemistry:</label>
            <input type="text" name="chemistry" id="chemistry2" class="form-control" [(ngModel)]=chemistry>
            <label for="enggdrawing2">Engg Drawing:</label>
            <input type="text" name="enggdrawing" id="enggdrawing2" class="form-control" [(ngModel)]=enggdrawing>
            <label for="math2">Maths:</label>
            <input type="text" name="maths" id="math2" class="form-control" [(ngModel)]=maths>
            <button type="submit" class="btn btn-warning" >Submit</button>
            </div>
    </form>
    </div>
  </div>
  </div>
</div>


</div>

.ts file
---------------

import { ComponentOnInit } from '@angular/core';

@Component({
  selector: 'app-adminresults',
  templateUrl: './adminresults.component.html',
  styleUrls: ['./adminresults.component.css']
})
export class AdminresultsComponent implements OnInit {
  abcany;

  constructor() { }

  ngOnInit() {
  }


data:object[]=[];
data2:object[]=[];

addResults(v)
{
  this.data.push(v);
}

edit(i,index)
{
this.data2=i;
this.abc=index;
}

update(v)
{
  this.data[this.abc]=v;
}

delete(i)
{
  this.data.splice(i,1)
}


}

app.module.ts
---------------------
import {FormsModulefrom '@angular/forms'

imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],

Saturday 1 February 2020

delete operation using database

app.delete('/users',(req,res)=>{
    //here the data is in req.body
    dbo.collection('users').remove({name:req.body.name},(err,success)=>{
        if(err) {
            console.log(err);
        }
        else {
            dbo.collection('users').find({}).toArray((err,data)=>{
                if(err) {
                    console.log(err)
                }
                else{
                    res.json(data);
                }
            })
        }
    })
})