{{announcement.body}}
{{announcement.title}}

MEAN Stack Example (Join and Quit the Event)

DZone 's Guide to

MEAN Stack Example (Join and Quit the Event)

This article introduces the main process of creating a small Angular application which has the function: Join the event to show your name; Quit to delete your name.

· Database Zone ·
Free Resource

This article will briefly introduce the main process of creating a small Angular application which has the function: Join the event to show your name; Quit to delete your name.

1. Mongo DB

Firstly, we need a database to store our data.

You can easily set up the MongoDB on the mLab which is a managed Database-as-a-Service platform. And insert the essential data we use here by typing:

db.events.save({"name":"Event","member":[]}); 

We have the events collection and insert one row of data to it.

2. Backend

Secondly, let's finish the backend section.

Usually, we have the server.js to run all the APIs. And the specific functions are written in different api.js files.

server.js:

A lot of libraries are used in the project to make it more efficient. You need to install all the dependencies first. You can easily do this by using npm, which is a package manager.

In the file server.js, we set up the server and import all the codes from api.js by using app.use().

const express = require('express');
const app = express();
const bodyParser = require('body-parser')
const cors = require('cors')
const PORT = 3000
const api = require('./routes/api')

app.use(cors())

app.use(bodyParser.json())

app.use('/api', api)

app.get('/', function (req, res) {
    res.send('HELLO FORM SERVER')
})

app.listen(PORT, function () {
    console.log('SERVER RUNNING ON LOCALHOST:' + PORT)
})

For api.js:

Mongoose is used here to interact with the MongoDB.

We firstly connect to the database.

Then find all the events, store in "events" and send data to frontend by "res.json(events)"

const express = require('express')
const router = express.Router()
const User = require('../models/user')
const UserInfo = require('../models/userInfo')
const Event = require('../models/event')

const mongoose = require('mongoose')
// Database address
const db = "mongodb://" 

// Connect to the database
mongoose.connect(db, err => {
    if (err) {
        console.error('Error!' + err)
    } else {
        console.log('Connected to Mogodb')
    }
})
router.get('/events', (req, res) => {
    Event.find(function (err, events) {
        if (err) return next(err);
        res.json(events);
    });
})

The join function:

First, read the 'req.body' from frontend and store it in "join".

Find the event according to the event name which is join.event.

Get the data from database and store the data in "eventJoin".

Push the username into the event member list.

eventJoin.save() will replace the previous data

router.post('/join', (req, res) => {
    let join = req.body;
    //find the event, add the user name into the member list
    Event.findOne({ name: join.event }, (err, eventJoin) => {
        if (!eventJoin) {
            res.json(join.event + "Not Found")
        }
        else {
            eventJoin.members.push(join.user);
            eventJoin.save();
        }
    })
})

The quit function:

First, read the "req.body" from frontend and store them in "quit".

Find the event according to the event name which is quit.event.

Get the data from the database and store the data in "eventQuit".

Find the index of the username and remove it from the list.

Replace the previous data.

//POST method for quit api
router.post('/quit', (req, res) => {
    let quit = req.body;
    Event.findOne({ name: quit.event }, (err, eventQuit) => {
        if (!eventQuit) {
            res.json(quit.event + "Not Found")
        }
        // find the event and delete the user name from the member list
        else {
            if (eventQuit.members.indexOf(quit.user) !== -1) {
                eventQuit.members.splice(eventQuit.membersID.indexOf(quit.user), 1);
                eventQuit.save();
            }
        }
    })
})

module.exports = router

3. Frontend

There will be three files in this section: event.html to display the elements, event.ts to do the function and event.service.ts to interact with the backend. 

The HTML file uses ngFor to show the list of  all the events.

Ngif will display the quit button if the user already joined the event and display join button if the user did not join it.

The event.members is the array where the member list is stored. Use include to check if the current user exists in the array and display the button accordingly.

When the button is clicked, the according function will be called. The event.name and userName will be passed to the function as the parameters. Both event and userName are data from event.ts.

  <div class="col-md-4 mb-3" *ngFor="let event of events">
    <div class="card text-center">
      <div class="card-body">
        <h5 class="card-title">{{event.name}}</h5>
        <p class="card-text">{{event.members}}</p>
      </div>
      <div class="card-footer text-muted">
        <button *ngIf="!event.members.includes(userName)" (click)="join(event.name,userName)"
          id="join" class="btn btn-lg btn-primary btn-block" type="submit">Join</button>
        <button *ngIf="event.members.includes(userName)" (click)="quit(event.name,userName)"
          id="quit" class="btn btn-lg btn-success btn-block " type="submit">Quit</button>
      </div>
    </div>
  </div>

The event.ts file contains the functions works for the HTML file.

Services are used to send the HTTP request and they will be explained in the next part.

In ngOnInit, first, use the getEvents() function from event.service.ts to get all the events and store the data in 'events'. Then display them in HTML by ngFor.

Join function stores the 'user' and 'event' values from HTML in the "userJoin", and call the join function from service with the parameter "userJoin". Reload the page to refresh the display.

Quit function stores the "user" and "event" values from html in the "userQuit", and call the Quit function from service with the parameter "userQuit". Reload the page to refresh the display.

import { EventService } from './../event.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-events',
  templateUrl: './events.component.html',
  styleUrls: ['./events.component.css']
})
export class EventsComponent implements OnInit {
  // initial variables
  events = [];
  userJoin = { user:"",event: "" };
  userQuit = { user:"", event: "" };
  userName= "DZone";

  constructor(private _eventService: EventService) {
  }

  ngOnInit() {
    //get all the event
     this._eventService.getEvents()
      .subscribe(
        res => {
        this.events = res;
        })
  }

  //join the event clicked, and refresh to show the new member list and quit button
  join(event, user) {
        this.userJoin.event = event;
        this.userJoin.user = user;
        this._eventService.join(this.userJoin).subscribe(
          res => this.userJoin = res
        )
        window.location.reload()
  }

  //quit the event clicked, and refresh to show the new member list and join button
  quit(event, user) {
    this.userQuit.event = event;
    this.userQuit.user = user;
    this._eventService.quit(this.userQuit).subscribe(
      res => this.userQuit = res
    )
    window.location.reload()
  }
}

The event.service.ts uses HttpClient to send the request:

The URLs store the addresses of different functions from the backend.

getEvents() is a get function that returns the data retrieved from backend.

Join and quit are post functions to pass data "user" to the backend and change the data on the database.

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable()
export class EventService {

  private _eventsUrl = "http://localhost:3000/api/events"
  private _joinUrl = "http://localhost:3000/api/join"
  private _quitUrl = "http://localhost:3000/api/quit"

  constructor(private http: HttpClient) { }

  getEvents() {
    return this.http.get<any>(this._eventsUrl)
  }

  join(user) {
    return this.http.post<any>(this._joinUrl, user)
  }
  quit(user) {
    return this.http.post<any>(this._quitUrl, user)
  }
}

Conclusion

The backend has the functions to get and change data on the database and interact with the database directly.

The front-end uses HTML to display the data, ts file to define the functions and service file to send requests to the backend and get responses to front-end.

You can find the quit and join functions as a part in my project dating-developers here.

Topics:
angular2, database, database tutorial, express, mongdb, nodejs, tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}