app.module.ts
----------------------
import {FormsModule} from '@angular/forms';
import {HttpClientModule} from '@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>
<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 { Component, OnInit } 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 { Component, OnInit } 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: false, timestamps: true});
module.exports=mongoose.model("notifications",notificationsSchema);
controllers/adminNotifications.js
------------------------------------------
const Notification = require("../models/notifications");
exports.createNotification = (req, res) => {
const notification = new Notification(req.body);
notification.save().then(result => {
res.json({
message: "notification added",
status: 200,
data: result
});
});
};
exports.getNotification = (req, res) => {
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 = (req, res) => {
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: true, useUnifiedTopology: 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}`)});