changeuserpassword.component.ts 2.88 KB
import { Component, OnInit, AfterViewInit } from '@angular/core';
import { ChangeUserPasswordService } from './changeuserpassword.service';
import { Router } from '@angular/router';
import { FormControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { User } from '../UpdateProfile/datamodel';
import { Http, Response } from '@angular/http';
//import { Global } from '../../Shared/global';
//import { DBOperation } from 'S';
//import { Observable } from 'rxjs/Observable';

@Component({
    templateUrl: './changeuserpassword.component.html'
})

export class ChangeUserPassword implements OnInit {

user: User;
changeUserPasswordFrm: FormGroup;
error: any;
alerts: string;

constructor(private changeUserPasswordService: ChangeUserPasswordService, private router: Router, private fb: FormBuilder) { }
  
    ngOnInit(): void {
        this.user = new User();
        this.alerts = '';
        this.changeUserPasswordFrm = this.fb.group({
            loginId: ['', Validators.required],
            oldPassword: ['', Validators.required],
            newPassword: ['', [Validators.required, Validators.minLength(8)]],
            confirmPassword: ['', Validators.required]
        });
        this.GetUserById();
    }

    GetUserById() {        
        this.changeUserPasswordService.GetUserById()
        .subscribe(x => { this.BindFormFields(x) }, error => this.error = error);    
    }

    public onFormSubmit() {
        if(this.user.Password != this.changeUserPasswordFrm.value.oldPassword){
            this.alerts = '<span>Old password is invalid</span>';
        }
        if(this.changeUserPasswordFrm.value.newPassword != this.changeUserPasswordFrm.value.confirmPassword){
            this.alerts += '</br><span>New password and confirm password must be same</span>';
        }
        if(this.alerts != ''){
            this.user = this.changeUserPasswordFrm.value;
            var obj = this.user
            return this.changeUserPasswordService.ChangeUserPassword(obj)
              .subscribe(
              n => (this.AfterInsertData(n)),
              error => this.error = <any>error);
        }
    }

    AfterInsertData(data) {
        if (data.Status == "false") {
            this.alerts = "<span>Password change unsuccessfull</span>";
        } else {
            this.alerts = "<span>Password changed successfully</span>";
        }
    }

    BindFormFields(data){
        this.user = data[0];
        this.changeUserPasswordFrm.controls['loginId'].setValue(this.user.LoginId);
    }

    ResetFormFields(){
        this.changeUserPasswordFrm.reset()
        this.changeUserPasswordFrm.controls['loginId'].setValue(this.user.LoginId);
        this.changeUserPasswordFrm.controls['oldPassword'].setValue('');
        this.changeUserPasswordFrm.controls['newPassword'].setValue('');
        this.changeUserPasswordFrm.controls['confirmPassword'].setValue('');
        this.alerts = '';
    }

}