Download our latest MNC Answers Application at Play Store. Download Now

Java Full Stack Developer - Angular 9 Hands-on Solution | TCS Fresco Play | TCS | MNC Answers

Java Full Stack Developer - Angular 9 Hands-on Solution | TCS Fresco Play | TCS | MNC Answers


Disclaimer: The primary purpose of providing this solution is to assist and support anyone who are unable to complete these courses due to a technical issue or a lack of expertise. This website's information or data are solely for the purpose of knowledge and education.

Make an effort to understand these solutions and apply them to your Hands-On difficulties. (It is not advisable that copy and paste these solutions).

All Question of the MCQs Present Below for Ease Use Ctrl + F with the question name to find the Question. All the Best!

*****************

Java Full Stack Developer - Angular 9 Hands-on solution

The Course Id is 63428.



1. all-patients-list.component.html


<app-header></app-header>

<div class="table-div">

  <table class="table-class">

    <thead>

      <tr class="table-head">

        <th>Patient ID</th>

        <th>FirstName</th>

        <th>LastName</th>

        <th>Gender</th>

        <th>DOB(yyyy-MM-dd)</th>

        <th>Mobile</th>

        <th>Email</th>

        <th>Registered on</th>

        <th>Update</th>

      </tr>

    </thead>

    <tbody>

      <!-- display all patients list -->

      <tr *ngFor="let item of allPatients" id="table-row">

        <td id="table-id">{{item.id}}</td>

        <td id="table-firstname" class="td-column">{{item.firstName}}</td>

        <td id="table-lastname">{{item.lastName}}</td>

        <td id="table-gender">{{item.gender}}</td>

        <td id="table-dob">{{item.dob}}</td>

        <td id="table-mobile">{{item.mobile}}</td>

        <td id="table-email">{{item.email}}</td>

        <td id="table-registeredOn">{{item.registeredTime| date: 'dd/MM/yyyy hh:mm:ss'}}</td>

        <td class="column-btn">

          <!--call view method with selected id when clicking this button-->

          <a id="view" class="view-details" (click)="view(item.id)">View Details</a>

        </td>

      </tr>

    </tbody>

  </table>

</div>



2.all-patients-list.component.ts


import { Component, OnInit } from '@angular/core';

import { Router } from '@angular/router';

import { Patient } from '../../models/patient';

import { DataService } from '../../services/data.service';

import { ActivatedRoute, RouterLinkActive } from '@angular/router';


@Component({

  selector: 'app-all-patients-list',

  templateUrl: './all-patients-list.component.html',

  styleUrls: ['./all-patients-list.component.css']

})

export class AllPatientsListComponent implements OnInit {


  allPatients: Patient[] = [];

  patient: Patient = null;

  constructor(private route: Router, private dataService: DataService) { }


  ngOnInit() {


    // get all patients list from service

    this.dataService.getAllPatientsList()

      .subscribe(data => {

        this.allPatients = data;

      });

  }


  view(patientId: number) {


    // should navigate to 'patientList' page with selected patientId

    this.route.navigate(['patientList', patientId]);

  }

}


3. all-requested-appointments.component.html


<app-header></app-header>

<div class="table-container">

  <table *ngIf="allAppointments" class="table-class">

    <thead>

      <tr class="table-head">

        <th>Appointment id</th>

        <th>Patient id</th>

        <th>Patient name</th>

        <th>Disease</th>

        <th>Priority</th>

        <th>Tentative date</th>

        <th>Requested on</th>

        <th>Update</th>

      </tr>

    </thead>

    <tbody>

      <!--display all appointments -->

      <tr *ngFor="let item of allAppointments" id="table-row">

        <td id="app-id">{{item.id}}</td>

        <td id="patient-id">{{item.patientId}}</td>

        <td id="patient-name">{{item.patientFirstName}} {{item.patientLastName}}</td>

        <td id="table-disease" class="td-column">{{item.disease}}</td>

        <td id="table-priority">{{item.priority}}</td>

        <td id="table-tentativedate">{{item.tentativedate| date: 'dd/MM/yyyy'}}</td>

        <td id="table-requestedOn">{{item.registeredTime| date: 'dd/MM/yyyy hh:mm:ss'}}</td>

        <td>

          <!--call view method with selected patient id when clicking this tag-->

          <a id="view" class="view-details" (click)="view(item.patientId)">View Details</a>

<!-- call cancelAppointment method with selected appointment id when clicking on this button-->

          <button id="reject" class="btn btn-danger btn-value" (click)="cancelAppointment(item.id)">Cancel

            Appointment

          </button>

        </td>

      </tr>

    </tbody>

  </table>

</div>


4. all-requested-appointments.component.ts


import { Component, OnInit } from '@angular/core';

import { DataService } from '../../services/data.service';

import { Router } from '@angular/router';

import { Appointment } from '../../models/appointment';


@Component({

  selector: 'app-all-requested-appointments',

  templateUrl: './all-requested-appointments.component.html',

  styleUrls: ['./all-requested-appointments.component.css']

})

export class AllRequestedAppointmentsComponent implements OnInit {


  allAppointments: Appointment[] = [];


  constructor(private dataService: DataService, private route: Router) {

  }


  ngOnInit() {

    // call appointments method by default

    this.appointments();

  }


  appointments() {


    // get all requested appointments from service

    this.dataService.requestedAppointments().subscribe(data => {

      this.allAppointments = data;

    })

  }


  view(patientId) {


    // should navigate to 'patientList' page with selected patientId

    // this.route.navigate(['patientlist', patientId]);

    this.route.navigate(['patientList', patientId]);


  }


  cancelAppointment(id) {


    // delete selected appointment uing service

    this.dataService.deleteAppointment(id).subscribe(data => {

      console.log(data);

      this.appointments();

    });

    // After deleting the appointment, get all requested appointments



  }


}


5.form.component.html


<!-- Write necessary code-->

<app-header></app-header>


<div id="form-container">

  <div class="form">

    <div class="form-content">

      <div class="col-sm-12 ">

        <div class="col-sm-8 div-header">

          <h2 class="header">Enter Patient details</h2>

        </div>


      </div>


      <!-- call submitForm method with all form values if form is valid -->

      <form [formGroup]="complexForm" (ngSubmit)="submitForm()">


        <div class="form-group">

          <label class="label-name">

            First Name:<span class="required">*</span>

          </label>

          <input id="firstname" class="form-control text-box" type="text" placeholder="FIRSTNAME"

            formControlName="firstName">

          <ng-container *ngIf="

                            complexForm.get('firstName').invalid &&

                            (complexForm.get('firstName').dirty ||

                                complexForm.get('firstName').touched)

                        ">

            <div *ngIf="complexForm.get('firstName').errors?.required" id="error-no-firstname"

              class="alert alert-danger error-msg">

              {{emptyFirstname}}

            </div>

            <div *ngIf="complexForm.get('firstName').errors?.minlength" id="error-minlength-firstname"

              class="alert alert-danger error-msg">

              {{minlengthFirstname}}

            </div>

            <div *ngIf="complexForm.get('firstName').errors?.maxlength" id="error-maxlength-firstname"

              class="alert alert-danger error-msg">

              {{maxlengthFirstname}}

            </div>

          </ng-container>

        </div>


        <div class="form-group">

          <label class="label-name">Last Name:

            <span class="required">*</span>

          </label>

          <input id="lastname" class="form-control text-box" type="text" placeholder="LASTNAME"

            formControlName="lastName">

          <ng-container *ngIf="

                            complexForm.get('lastName').invalid &&

                            (complexForm.get('lastName').dirty ||

                                complexForm.get('lastName').touched)

                        ">

            <div *ngIf="complexForm.get('lastName').errors?.required" id="error-no-lastname"

              class="alert alert-danger error-msg">

              {{emptyLastname}}

            </div>

            <div *ngIf="complexForm.get('lastName').errors?.minlength" id="error-minlength-lastname"

              class="alert alert-danger error-msg">

              {{minlengthLastname}}

            </div>

            <div *ngIf="complexForm.get('lastName').errors?.maxlength" id="error-maxlength-lastname"

              class="alert alert-danger error-msg">

              {{maxlengthLastname}}

            </div>

          </ng-container>

        </div>


        <div class="form-group">

          <label class="label-name">Gender:

            <span class="required">*</span>

          </label>

          <div class="input-div">

            <input type="radio" id="male" class="input-content" value="Male" formControlName="gender">

            <label class="label-content" for="male">Male</label>

<input type="radio" id="female" class="input-content" value="Female" formControlName="gender">

            <label class="label-content" for="female">Female</label>

          </div>

          <ng-container *ngIf=" complexForm.get('lastName').invalid &&

                                                                    (complexForm.get('lastName').dirty ||

                                                                        complexForm.get('lastName').touched)

                                                                ">

            <div *ngIf="complexForm.get('gender').errors?.required" id="error-no-gender"

              class="alert alert-danger error-msg">

              {{noGender}}

            </div>

          </ng-container>

        </div>


        <div class="form-group">

          <label class="label-name">

            Date of birth:<span class="required">*</span>

          </label>

          <div>

            <input id="date-input" class="form-control date-input glyphicon glyphicon-calendar" type="date"

              placeholder="Date of birth" min="1968-01-01" max="{{today}}" formControlName="dob">

          </div>

          <ng-container *ngIf="

                            complexForm.get('dob').invalid &&

                            (complexForm.get('dob').dirty ||

                                complexForm.get('dob').touched)

                        ">


            <div id="error-no-dob" class="alert alert-danger error-msg">

              {{noDob}}

            </div>

          </ng-container>

        </div>


        <div class="form-group">

          <label class="label-name">

            Contact number:<span class="required">*</span>

          </label>

          <input id="mobile" class="form-control text-box" type="text" placeholder="mobile number"

            formControlName="mobile">

          <ng-container *ngIf="

                            complexForm.get('mobile').invalid &&

                            (complexForm.get('mobile').dirty ||

                                complexForm.get('mobile').touched)

                        ">


            <div *ngIf="complexForm.get('mobile').errors?.required" id="error-no-mobile"

              class="alert alert-danger error-msg">

              {{noMobile}}

            </div>

            <div *ngIf="complexForm.get('mobile').errors?.pattern" id="error-number-mobile"

              class="alert alert-danger error-msg">

              {{numberMobile}}

            </div>

            <div *ngIf="complexForm.get('mobile').errors?.maxlength" id="error-maxlength-mobile"

              class="alert alert-danger error-msg">

              {{maxlengthMobile}}

            </div>

          </ng-container>

        </div>


        <div class="form-group">

          <label class="label-name" for="email">

            Email:<span class="required">*</span>

          </label>

          <input id="email" class="form-control text-box" type="email" placeholder="example:abc12@tcs.com"

            formControlName="email">

          <ng-container *ngIf="

                                                complexForm.get('email').invalid &&

                                                (complexForm.get('email').dirty ||

                                                    complexForm.get('email').touched)

                                            ">

            <div *ngIf="complexForm.get('email').errors?.required" id="error-no-email"

              class="alert alert-danger error-msg">

              {{noEmail}}

            </div>

            <div *ngIf="complexForm.get('email').errors?.pattern" id="error-pattern-email"

              class="alert alert-danger error-msg">

              {{patternEmail}}

            </div>

          </ng-container>


        </div>


        <div class="form-group">

          <label class="label-name" for="description">

            Description: <span class="xs-font">(Optional)</span>

          </label>

          <textarea id="description" class="form-control " placeholder="Briefly describe the issue"></textarea>

        </div>


        <div class="form-group">

          <!-- disable button if form not valid -->

          <button type="submit" id="submit-btn" class="btn btn-primary submit-btn"

            [disabled]="!complexForm.valid">Submit</button>

        </div>


      </form>

    </div>

  </div>

</div>


6.form.component.ts


import { Component, OnInit, Input } from '@angular/core';

import { FormGroup, FormBuilder, Validators } from '@angular/forms';

import { DatePipe } from '@angular/common';

import { Router } from '@angular/router';

import { Patient } from '../../models/patient';

import { DataService } from '../../services/data.service';


@Component({

  selector: 'app-form',

  templateUrl: './form.component.html',

  styleUrls: ['./form.component.css'],

  providers: [DatePipe]

})

export class FormComponent implements OnInit {


  complexForm: FormGroup;

  patientDetails = new Patient;

  today: string;

  result;


  noRecordsFound = 'No patient records found in the list. Click on Register New Patient to add Patient details.';


  emptyFirstname = 'You must include a first name.';

  minlengthFirstname = 'Your first name must be at least 3 characters long.';

  maxlengthFirstname = 'Your first name cannot exceed 20 characters.';

  emptyLastname = 'You must include a last name.';

  minlengthLastname = 'Your last name must be at least 3 characters long.';

  maxlengthLastname = 'Your last name cannot exceed 20 characters.';

  noGender = 'You must select a gender.';

  noDob = 'You must select a valid date of birth.';

  noMobile = 'You must include mobile number.';

  numberMobile = 'You must enter a valid 10 digit mobile number.';

  maxlengthMobile = 'Your mobile number should not exceed 10 digits.';

  noEmail = 'You must include a valid email.';

  patternEmail = 'Pattern does not match.';


  ngOnInit() {

    this.today = this.datePipe.transform(Date.now(), 'yyyy-MM-dd');

  }


  constructor(fb: FormBuilder, private datePipe: DatePipe, private route: Router, private dataService: DataService) {


    // add necessary validators


    this.complexForm = fb.group({

      firstName: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(20)]],

      lastName: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(20)]],

      gender: [null, Validators.required],

      dob: [null, Validators.required],

      mobile: ['', [Validators.required, Validators.minLength(10), Validators.maxLength(10), Validators.pattern(/^\d{10,}$/)]],

      email: ['', [Validators.required, Validators.email, Validators.pattern(/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/)]],

      description: ''

    });

  }


  submitForm(value: any) {


    // assign new date object to reportedTime

    // should reister new patient using service

    // if added successfully should redirect to 'patientList' page


  }


}


7.header.component.html


<nav class="navbar navbar-default">

  <div class="container-fluid">

    <div class="navbar-header">

      <a class="navbar-brand">Health Care Service</a>

      <label class="navbar-brand">

        <span class="glyphicon glyphicon-user"></span> Welcome

        <span id="username" class="user">{{userDetails.username}}</span>

      </label>

    </div>

    <div class="nav-left">

      <ul class="nav navbar-nav">

        <li>

          <a routerLink="/profile" routerLinkActive="current-link">

            <span class="glyphicon glyphicon-cog"></span> Profile

          </a>

        </li>

        <li>

          <a routerLink="/form" routerLinkActive="current-link">

            <i class="fa fa-wpforms" aria-hidden="true"></i>

            Register patient

          </a>

        </li>

        <li>

          <a routerLink="/patientList" routerLinkActive="current-link">

            <span class="glyphicon glyphicon-th-list"></span> Viewall patients

          </a>

        </li>

        <li>

          <a routerLink="/requested_appointments" routerLinkActive="current-link">

            <span class="glyphicon glyphicon-list-alt"></span> Requested App

          </a>

        </li>

        <li>

          <a routerLink="/login">

            <span class="glyphicon glyphicon-log-out" routerLinkActive="current-link"></span> Logout

          </a>

        </li>

      </ul>

    </div>

  </div>

</nav>



8. header.component.ts


import { Component, OnInit } from '@angular/core';

import { DataService } from '../../services/data.service';

import { Users } from '../../models/users.model';

import { ActivatedRoute } from '@angular/router';


@Component({

  selector: 'app-header',

  templateUrl: './header.component.html',

  styleUrls: ['./header.component.css']

})

export class HeaderComponent implements OnInit {


  userId = -1;

  private userDetails = new Users;


  constructor(private dataService: DataService) {


  }


  ngOnInit() {


    // get userId from service and assign it to userId property

    this.userId = this.dataService.getUserId();

    // call getProfileDetails method to get user details

    this.getProfileDetails();

  }


  getProfileDetails() {


    // call getUserDetails method of dataService and assign response to userDetails property

    this.dataService.getUserDetails(this.userId)

      .subscribe(data => {

        this.userDetails = data;

      });


  }



}


9.login.component.html


<!-- Write necessary code-->

<div class="login-view-wrapper custom-container">

  <div class="login-view">

    <div class="logo-wrapper">

      <img src="./../assets/login.png" width="100" height="100" />

      <h2>LOGIN</h2>

    </div>

    <div class="login-form-wrapper">

      <form class="ro-form" [formGroup]="loginForm">

        <div class="form-group">

          <label class="labelHead" for="username">

            <b>Username</b>

          </label>

          <input type="text" id="username" placeholder="userName" formControlName="userName" />


          <ng-container *ngIf="

                            loginForm.get('userName').invalid &&

                            (loginForm.get('userName').dirty ||

                                loginForm.get('userName').touched)

                        ">

            <div *ngIf="loginForm.get('userName').errors?.required" class="form-error-messages" id="error-no-username">

              {{ emptyUserName }}

            </div>

            <div *ngIf="loginForm.get('userName').errors?.minlength" class="form-error-messages"

              id="error-minlength-username">

              {{ minlengthUserName }}

            </div>

            <div *ngIf="loginForm.get('userName').errors?.maxlength" class="form-error-messages"

              id="error-maxlength-username">

              {{ maxlengthUserName }}

            </div>

            <div *ngIf="loginForm.get('userName').errors?.pattern" class="form-error-messages"

              id="error-pattern-username">

              {{ userNamePattern }}

            </div>

          </ng-container>

        </div>

        <div class="form-group">

          <label class="labelHead" for="password">

            <b>Password</b>

          </label>

          <input type="password" id="password" placeholder="password" formControlName="password" />

          <ng-container *ngIf="

                            loginForm.get('password').invalid &&

                            (loginForm.get('password').dirty ||

                                loginForm.get('password').touched)

                        ">

            <div *ngIf="loginForm.get('password').errors?.required" class="form-error-messages" id="error-no-password">

              {{ emptyPassword }}

            </div>

            <div *ngIf="loginForm.get('password').errors?.minlength" class="form-error-messages"

              id="error-minlength-password">

              {{ minlengthPassword }}

            </div>

            <div *ngIf="loginForm.get('password').errors?.maxlength" class="form-error-messages"

              id="error-maxlength-password">

              {{ maxlengthPassword }}

            </div>

            <div *ngIf="loginForm.get('password').errors?.pattern" class="form-error-messages"

              id="error-pattern-password">

              {{ passwordPattern }}

            </div>

          </ng-container>

        </div>

        <div class="col-sm-12 clmn12">

          <!-- disable button if form not valid -->

          <!-- call doLogin method when clicking on this button-->

          <button id="loginBtn" class="login-btn" type="submit" (click)="doLogin()" [disabled]="!loginForm.valid">

            Login

          </button>

        </div>

      </form>

    </div>

  </div>

</div>


10. login.component.ts


import { Component, OnInit } from '@angular/core';

import { FormControl, FormGroup, Validators } from '@angular/forms';

import { Router } from '@angular/router';

import { DataService } from '../../services/data.service';


@Component({

  selector: 'app-login',

  templateUrl: './login.component.html',

  styleUrls: ['./login.component.css']

})

export class LoginComponent implements OnInit {


  isLoggedIn: boolean = false;

  loginForm: FormGroup;

  isLoginFailed: boolean = false;



  emptyUserName = 'You must enter a username';

  minlengthUserName = 'User name must be at least 3 characters long';

  maxlengthUserName = 'Username cannot exceed 20 characters';

userNamePattern = 'Username should be in alphanumeric only';

  emptyPassword = 'You must enter a password';

  minlengthPassword = 'Password must be at least 8 characters long';

  maxlengthPassword = 'Password cannot exceed 20 characters';

  passwordPattern = 'Pattern does not match';

  wrongCredentials = 'Incorrect Username or Password';


  constructor(private route: Router, private dataService: DataService) {

  }


  ngOnInit() {


    // add necessary validators


    this.loginForm = new FormGroup({

      userName: new FormControl('', [

        Validators.required,

        Validators.minLength(3),

        Validators.maxLength(20),

        Validators.pattern(/^[a-zA-Z0-9]*$/)

      ]),

      password: new FormControl('', [

        Validators.required,

        Validators.minLength(8),

        Validators.maxLength(20),

        Validators.pattern(/^[a-zA-Z0-9!$%@#*?&£€]*$/)

      ])

    });

  }


  doLogin() {

    // call authenticateUser method to perform login operation

    this.dataService.authenticateUser(this.loginForm.get('userName').value, this.loginForm.get('password').value)

      .subscribe(data => {

        if (data) {

          // if success, redirect to profile page

          this.route.navigate(['/profile']);

        } else {

          // else display appropriate error message

          this.isLoginFailed = true;

          // reset the form

          this.loginForm.reset();

        }

      }, err => {

        this.isLoginFailed = true;

        console.log(err);

      });

  }

}


11. profile.component.html


<!-- Write necessary code-->

<app-header></app-header>

<div class="main-view">

  <div class="home-content-wrapper">

    <div class="home-profile-wrapper">

      <div class="profile-details">

        <img [src]="userImg" width="120" height="100" class="profile-img">

      </div>

    </div>

    <div class="home-profile-wrapper border">


      <!-- hide profile details if editing the form-->

      <ul *ngIf="!editProfile" id="profileDetails" class="profile-details">

        <li class="list-items">

          <fa class="home-icons" name="user" size="2x"></fa>

          <span id="usernameVal">

            {{userDetails?.username}}

          </span>


        </li>

        <li class="list-items">

          <fa class="home-icons fa-icon " name="mobile" size="2x"></fa>

          <span id="mobileVal">

            {{userDetails?.mobile}}

          </span>

        </li>

        <li class="list-items">

          <fa class="home-icons fa-icon" name="envelope" size="2x"></fa>

          <span id="emailVal" class="list-items">

            {{userDetails?.email}}

          </span>

        </li>

        <li class="list-items">

          <fa class="home-icons" name="map-marker" size="2x"></fa>

          <span id="locationVal" class="list-items">

            {{userDetails?.location}}

          </span>

        </li>

      </ul>


      <!-- show edit profile form if edit profile button clicked-->

      <form *ngIf="editProfile" id="editProfileForm" class="ro-form profile-form" [formGroup]="editProfileForm">

        <h2>Edit your profile</h2>

        <div class="form-group">

          <label for="username">

            Name

          </label>

          <input type="text" id="consumerName" formControlName="userName" value="" placeholder="Name">


        </div>

        <div class="form-group">

          <label for="mobile">

            Contact number

          </label>

          <input type="text" value="" id="mobile" formControlName="mobile" placeholder="mobile number">

          <div *ngIf="editProfileForm.get('mobile').errors" class="form-error-messages">

            {{mobileErrMsg}}

          </div>

        </div>

        <div class="form-group">

          <label for="email">

            Email

          </label>

          <input type="email" value="" formControlName="email" id="email" placeholder="Email">

          <div *ngIf="editProfileForm.get('email').errors" class="form-error-messages">

            {{emailErrMsg}}

          </div>

        </div>


        <div class="form-group">

          <label for="location">

            Location

          </label>

          <input type="text" value="" id="location" formControlName="location" placeholder="Location">

          <div *ngIf="editProfileForm.get('location').errors" class="form-error-messages">

            {{locationErrMsg}}

          </div>

        </div>


        <!-- disable button if form not valid -->

        <!-- call changeMyProfile method when clicking on this button-->

        <button [disabled]="!editProfileForm.valid" (click)="changeMyProfile()" class="btn" type="submit"

          id="editSubmitBtn">Make changes</button>

      </form>

      <div class="profile-edit-choice">


        <!-- show button if not editing the form-->

        <!-- call editMyProfile method when clicking on this button-->

        <button *ngIf="!editProfile" (click)="editMyProfile()" id="editProfileBtn" class="prompt-btn btn">

          Edit profile</button>


        <!-- show button if editing the form-->

        <!-- call discardEdit method when clicking on this button-->

        <button *ngIf="editProfile" (click)="discardEdit()" id="editDiscardBtn" class="alert-btn btn">Discard</button>

      </div>

    </div>

  </div>

</div>


12. profile.component.ts


import { Component, OnInit } from '@angular/core';

import { FormControl, FormGroup, Validators } from '@angular/forms';


import { Users } from '../../models/users.model';

import { DataService } from '../../services/data.service';



@Component({

  selector: 'app-profile',

  templateUrl: './profile.component.html',

  styleUrls: ['./profile.component.css']

})


export class ProfileComponent implements OnInit {


  // used as a flag to display or hide form

  editProfile = false;

  userId = -1;

  userDetails = new Users;


  editProfileForm: FormGroup;

  userImg = './../../assets/user.jpg';

  mobileErrMsg = 'You must enter a valid mobile number';

  emailErrMsg = 'You must enter a valid Email ID';

  locationErrMsg = 'You must enter the location';


  constructor(private dataService: DataService) { }


  ngOnInit() {


    // add necessary validators

    // username should be disabled. it should not be edited


    this.editProfileForm = new FormGroup({

      userName: new FormControl({ value: '', disabled: true }, Validators.required),

      mobile: new FormControl('', [Validators.minLength(10), Validators.maxLength(10)]),

      email: new FormControl('', Validators.email),

      location: new FormControl('', Validators.required)

    });


    // get login status from service

    // get userId from service and assign it to userId property

    this.userId = this.dataService.getUserId();

    // get profile details and display it

    this.getProfileDetails();

  }


  changeMyProfile() {


    // if successfully changed the profile it should display new details hiding the form

    this.dataService.updateProfile({

      userId: this.userId,

      username: this.editProfileForm.get('userName').value,

      mobile: this.editProfileForm.get('mobile').value,

      email: this.editProfileForm.get('email').value,

      location: this.editProfileForm.get('location').value,

    }).subscribe(data => {

      if (data) {

        this.discardEdit();

        this.getProfileDetails();

      } else {


      }

    }, err => {


    });


  }


  editMyProfile() {

    // change editProfile property value appropriately

    this.editProfile = true;

    this.editProfileForm.setValue({

      userName: this.userDetails.username,

      email: this.userDetails.email,

      location: this.userDetails.location,

      mobile: this.userDetails.mobile

    });

  }


  discardEdit() {

    // change editProfile property value appropriately

    this.editProfile = false;

  }


  getProfileDetails() {


    // retrieve user details from service using userId

    this.dataService.getUserDetails(this.userId)

      .subscribe(data => {

        this.userDetails = data;


      }, err => {

        this.userDetails = new Users();

      });


  }


}


13.patient.component.html


<!-- Write necessary code-->

<app-header></app-header>


<div class="view-container" *ngIf="patient">


  <div class="details-container">

    <h2 class="view-header" style="font-weight: bold;">Patient Details</h2>

    <div class="div-name">

      ID:<span class="details">{{patient.id}}</span>

    </div>

    <div class="div-name">

      Name:<span class="name">{{patient.firstName}} {{patient.lastName}}</span>

    </div>

    <div class="div-name">

      Gender:<span class="details">{{patient.gender}}</span>

    </div>

    <div class="div-name">

      Date of birth:<span class="details">{{patient.dob}}</span>

    </div>

    <div class="div-name">

      Mobile:<span class="details">{{patient.mobile}}</span>

    </div>

    <div class="div-name">

      Email:<span class="details">{{patient.email}}</span>

    </div>

    <div class="div-name">

      Registered on:<span class="details">{{patient.registeredTime| date: 'dd/MM/yyyy hh:mm:ss'}}</span>

    </div>

    <div class="update">


      <!-- disable the same when clicking on this button -->

      <!-- call bookAppointment method when clicking on this button-->

      <button id="book-appointment" class="btn btn-success book-btn" (click)="bookAppointment()"

        [disabled]="!isBookAppointment">Book Appointment</button>




      <!-- disable the same when clicking on this button -->

      <!-- call scheduledAppointment method when clicking on this button-->

      <button id="Scheduled-appointment" class="btn btn-warning book-btn" (click)="scheduledAppointment()"

        [disabled]="!isScheduledAppointment">Scheduled Appointment</button>

    </div>

  </div>


  <!-- show book appointment form if "Book Appointment" button clicked-->

  <!-- call scheduleAppointment method if form is valid-->

  <form *ngIf="isFormEnabled" id="form-container" class="form-container" [formGroup]="appointmentForm"

    (click)="scheduleAppointment()">

    <h2 class="view-header" style="padding-left: 100px">Book Appointment</h2>

    <div class="form-content">


      <div class="form-content2">

        <div class="form-group ">

          <label class="label-name">

            Select Disease:<span class="required">*</span>

          </label>

          <div>

            <select id="select-selectDisease" class="text-box select" formControlName="selectDisease">

              <option class="label-content" value="null" disabled="true">Select disease</option>

              <!-- display diseases list-->

              <option *ngFor="let item of names" id="option-value" class="label-content">{{item.name}}

              </option>

            </select>

          </div>

          <div id="error-no-selectDisease" class="alert alert-danger error-msg">

            noselectDisease

          </div>

        </div>


        <div class="form-group ">

          <label class="label-name">

            Priority:<span class="required">*</span>

          </label>

          <div>

            <select id="priority" class="text-box select" formControlName="priority">

              <option class="label-content" value="null" disabled="true">Select priority</option>

              <option id="normal" class="label-content" value="Normal">Normal</option>

              <option id="urgent" class="label-content" value="Urgent">Urgent</option>

            </select>

          </div>

          <div id="error-no-priority" class="alert alert-danger error-msg">

            nopriority

          </div>

        </div>


        <div class="form-group">

          <label class="label-name">

            tentativeDate:<span class="required">*</span>

          </label>

          <div>

            <input id="date-input" class="form-control date-input glyphicon glyphicon-calendar" type="date"

              placeholder="tentativeDate" min="{{today}}" formControlName="tentativeDate">

          </div>

          <div id="error-no-tentativeDate" class="alert alert-danger error-msg">

            notentativeDate

          </div>

        </div>

      </div>

      <div class="form-group">

        <!-- disable button if form not valid -->

        <button type="submit" id="submit-btn" class="btn btn-primary submit-btn">Schedule</button>

      </div>

    </div>

  </form>



  <!-- show Scheduled Appointment table if "Scheduled Appointment" button clicked-->

  <div *ngIf="isTableEnabled" id="table-container" class="table-container">

    <h2 class="view-header">Scheduled Appointment</h2>

    <!-- display no records found message if there is no appointment -->

    <div *ngIf="!scheduledAppointments" class="no-records">No Records Found</div>

    <table *ngIf="scheduledAppointments" class="table-class">

      <thead>

        <tr class="table-head">

          <th>Appointment id</th>

          <th>Disease</th>

          <th>Priority</th>

          <th>Tentative date</th>

          <th>Requested on</th>

          <th>Update</th>

        </tr>

      </thead>

      <tbody>

        <!--display scheduled appointments-->

        <tr *ngFor="let item of scheduledAppointments" id="table-row">

          <td id="table-id">{{item.id}}</td>

          <td id="table-disease" class="td-column">{{item.disease}}</td>

          <td id="table-priority">{{item.priority}}</td>

          <td id="table-tentativedate">{{item.tentativedate| date: 'dd/MM/yyyy'}}</td>

          <td id="table-requestedOn">{{item.registeredTime| date: 'dd/MM/yyyy hh:mm:ss'}}</td>

          <td class="column-btn">


            <!-- call cancelAppointment method with selected id when clicking on this button-->

            <button id="user-cancel" class="btn btn-danger btn-spc" (click)="cancelAppointment(item.id)">

              <span class="btn-value">Cancel Appointment</span>

            </button>

          </td>

        </tr>

      </tbody>

    </table>

  </div>


</div>


14. view-patient.component.ts


import { Component, OnInit } from '@angular/core';

import { DataService } from '../../services/data.service';

import { FormGroup, FormBuilder } from '@angular/forms';

import { Router, ActivatedRoute } from '@angular/router';

import { DatePipe } from '@angular/common';

import { Appointment } from '../../models/appointment';


@Component({

  selector: 'app-view-patient',

  templateUrl: './view-patient.component.html',

  styleUrls: ['./view-patient.component.css'],

  providers: [DatePipe]

})

export class ViewPatientComponent implements OnInit {


  patient = null;

  names = [];

  today;

  isBookAppointment = true;

  isScheduledAppointment = true;


  isFormEnabled = false;

  isTableEnabled = false;

  appointmentForm: FormGroup;

  appointmentDetails = new Appointment;

  bookedAppointmentResponse;

  ScheduledAppointmentResponse;


  scheduledAppointments: Appointment[] = [];


  constructor(

    fb: FormBuilder,

    private route: Router,

    private datePipe: DatePipe,

    private activatedRoute: ActivatedRoute,

    private dataService: DataService) {

    this.today = this.datePipe.transform(Date.now(), 'yyyy-MM-dd');

    // add necessary validators

    this.appointmentForm = fb.group({

      selectDisease: [null],

      tentativeDate: [null],

      priority: [null]

    });


  }


  ngOnInit() {


    // get selected patient id

    this.activatedRoute.params.subscribe((params: { id: string }) => {

      // get Particular Patient from service using patient id and assign response to patient property

      this.dataService.getParticularPatient(parseInt(params.id, 10))

        .subscribe(data => {

          this.patient = data;

        });

    });


  }


  bookAppointment() {

    // get diseases list from service

    this.dataService.getDiseasesList().subscribe(data => {

      this.names = data;

    });

    // change isBookAppointment, isScheduledAppointment, isFormEnabled, isTableEnabled property values appropriately

    this.isBookAppointment = false;

    this.isFormEnabled = true;

    this.isScheduledAppointment = true;

    this.isTableEnabled = false;

  }


  scheduleAppointment() {


    // The below attributes to be added while booking appointment using service

    // patientId, patientFirstName, patientLastName, disease, priority, tentativedate, registeredTime


    const appointment = {

      patientFirstName: this.patient.firstName,

      patientLastName: this.patient.lastName,

      disease: this.appointmentForm.get('selectDisease').value,

      priority: this.appointmentForm.get('priority').value,

      tentativedate: this.appointmentForm.get('tentativeDate').value

    };


    // if booked successfully should redirect to 'requested_appointments' page

    this.dataService.bookAppointment(appointment)

      .subscribe(data => {

        if (data) {

          this.route.navigate(['/requested_appointments']);

        }

      }, err => {

        console.log(err);

      });

  }


  scheduledAppointment() {


    // change isBookAppointment, isScheduledAppointment, isFormEnabled, isTableEnabled property values appropriately

    this.isBookAppointment = true;

    this.isScheduledAppointment = false;

    this.isTableEnabled = true;

    this.isFormEnabled = false;


    // get particular patient appointments using getAppointments method of DataService

    this.dataService.getAppointments(this.patient.id).subscribe(data => {

      this.scheduledAppointments = data;

    });


  }


  cancelAppointment(id) {


    // delete selected appointment uing service

    this.dataService.deleteAppointment(id)

      .subscribe(data => {


      });

    // After deleting the appointment, get particular patient appointments


  }


}


15. api.service.ts


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

import { Inject, Injectable } from '@angular/core';


import { Credentials } from '../models/credentials.model';

import { Users } from '../models/users.model';

import { Patient } from '../models/patient';

import { Appointment } from '../models/appointment';

import { Observable, throwError } from 'rxjs';

import { catchError } from 'rxjs/operators';


@Injectable()

export class ApiService {


  API_URL: string;

  AUTH_API_URL = '/auth/server/';

  allPatients: Patient[] = [];

  appointments: Appointment[] = [];

  users: Users[] = [];

  authUsers: {

    id: number;

    username: string;

    password: string;

  }[] = [];


  constructor(private http: HttpClient) {

    this.API_URL = 'api';

  }


  public checkLogin(username: string, password: string): Observable<Credentials> {

    return this.http.post<Credentials>(this.API_URL + this.AUTH_API_URL, { username, password });

  }


  public getUserDetails(userId: number): Observable<Users> {

    // should return user details retireved from server

    return this.http.get<Users>(this.API_URL + '/users/' + userId).pipe(catchError(this.handleError));

    // handle error

  }


  public updateDetails(userDetails: Users): Observable<Users> {

    // should return user details if successfully updated the details


    // handle error


    return this.http.put<Users>(this.API_URL + '/users/' + userDetails.userId, userDetails);

  }


  public registerPatient(patientDetails: any): Observable<any> {

    // should return response from server if patientDetails added successfully

    // handle error

    return this.http.post<Patient>(this.API_URL + '/allpatients', patientDetails).pipe(catchError(this.handleError));

  }


  public getAllPatientsList(): Observable<any> {

    // should return all patients from server

    // handle error

    return this.http.get<any>(this.API_URL + '/allpatients');

  }


  public getParticularPatient(id: number): Observable<any> {

    // should return particular patient details from server

    // handle error

    return this.http.get<any>(this.API_URL + '/allpatients/' + id);

  }


  public getDiseasesList(): Observable<any[]> {

    // should return diseases from server

    // handle error

    return this.http.get<any[]>(this.API_URL + '/diseases');

  }


  public bookAppointment(appointmentDetails): Observable<any> {


    // should return response from server if appointment booked successfully


    // handle error


    return this.http.post<Appointment>(this.API_URL + '/reqappointments', appointmentDetails);

  }


  public requestedAppointments(): Observable<any> {


    // should return all requested appointments from server


    // handle error


    return this.http.get<Appointment[]>(this.API_URL + '/reqappointments');

  }


  public getAppointments(userId): Observable<any> {


    // should return appointments of particular patient from server


    // handle error


    return this.http.get<Appointment[]>(this.API_URL + '/reqappointments?patientId=' + userId).pipe(catchError(this.handleError));

  }


  public deleteAppointment(appointmentId): Observable<any> {

    // should delete the appointment

    // handle error

    return this.http.delete<void>(this.API_URL + '/reqappointments/' + appointmentId).pipe(catchError(this.handleError));

  }


  private handleError(error: Response | any) {

    return throwError(error);

  }


}


16. data.service.ts



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

import { BehaviorSubject, Observable, throwError } from 'rxjs';

import { catchError, map } from 'rxjs/operators';

import { Users } from '../models/users.model';


import { ApiService } from './api.service';


@Injectable()

export class DataService {


  isLoggedIn = false;

  isLogIn: BehaviorSubject<boolean>;

  constructor(private api: ApiService) {

    this.isLogIn = new BehaviorSubject<boolean>(false);

    this.isLogIn.subscribe(data => {

      if (!data) {

        // localStorage.removeItem('userId');

      }

    });

  }


  authenticateUser(username: string, password: string): Observable<boolean> {

    return this.api.checkLogin(username, password)

      .pipe(map(data => {

        if (data && data.userId) {

          // store 'userId' from response as key name 'userId' to the localstorage

          localStorage.setItem('userId', data.userId + '');

          // return true if user authenticated

          this.isLogIn.next(true);

          return true;

        } else {

          // return false if user not authenticated

          return false;

        }

      }));

  }


  getAuthStatus(): Observable<boolean> {

    this.isLogIn.next(this.getUserId() > 0 ? true : false);

    return this.isLogIn.asObservable(); // passed

  }

  doLogOut() {

    // remove the key 'userId' if exists

    this.isLoggedIn = false;

    if (localStorage.getItem('userId')) {

      localStorage.removeItem('userId');

    }

    this.isLogIn.next(false);

    return this.isLoggedIn;

  }


  getUserDetails(userId: number): Observable<Users> {

    // should return user details retrieved from api service

    return this.api.getUserDetails(userId);

  }


  updateProfile(userDetails): Observable<boolean> {

    // should return the updated status according to the response from api service

    return this.api.updateDetails(userDetails)

      .pipe(map(data => data ? true : false), catchError(this.handleError));

  }


  registerPatient(patientDetails): Observable<any> {

    // should return response retrieved from ApiService

    // handle error

    return this.api.registerPatient(patientDetails);

  }


  getAllPatientsList(): Observable<any> {

    // should return all patients list retrieved from ApiService

    // handle error

    return this.api.getAllPatientsList();

  }


  getParticularPatient(id: number): Observable<any> {

    // should return particular patient details retrieved from ApiService

    // handle error

    return this.api.getParticularPatient(id);

  }


  getDiseasesList(): Observable<any> {

    // should return response retrieved from ApiService

    // handle error

    return this.api.getDiseasesList();

  }


  bookAppointment(appointmentDetails): Observable<any> {

    // should return response retrieved from ApiService

    // handle error

    return this.api.bookAppointment(appointmentDetails);

  }


  getAppointments(patientId): Observable<any> {

    // should return response retrieved from ApiService

    // handle error

    return this.api.getAppointments(patientId);

  }


  deleteAppointment(appointmentId): Observable<any> {

    // should return response retrieved from ApiService

    // handle error

    return this.api.deleteAppointment(appointmentId);

  }


  requestedAppointments(): Observable<any> {


    // should return response retrieved from ApiService

    // handle error

    return this.api.requestedAppointments();

  }


  getUserId(): number {

    // retrieve 'userId' from localstorage

    const userId = parseInt(localStorage.getItem('userId'), 10);

    if (!this.isLogIn.value)

      return -1;

    return userId ? userId : -1;

  }

  private handleError(error: Response | any) {

    return throwError(error);

  }

}




**************************************************
Credit for the above notes, goes to the respective owners. 

If you have any queries, please feel free to ask on the comment section.
If you want MCQs and Hands-On solutions for any courses, Please feel free to ask on the comment section too.

Please share and support our page!