Angular 聲明對象, 指定合適的類型

    // selectedSuburbItem:Object;
    // selectedSuburbItem:Object = {
    //     suburb: "", 
    //     postcode: "", 
    //     state: ""
    // }
   
    // selectedSuburbItem:any = {
    //     suburb: "", 
    //     postcode: "", 
    //     state:  ""
    // }
    // selectedCountryItem:object[];

    selectedSuburbItem:any;


    selectedCountryItem:Array<any> = new Array();
import {Component, OnInit} from '@angular/core';
import {AbstractControl, FormBuilder, FormGroup, Validators} from '@angular/forms';
import {ActivatedRoute, Router} from '@angular/router';
import {RegisterService} from './register.service';
import {TranslateService} from '@ngx-translate/core';
import {locale as chinese} from '../../shared/shared-i18n/cn';
import {locale as english} from '../../shared/shared-i18n/en';
import {MatSnackBar} from '@angular/material';
import {postcodeValidator} from '../../shared/directive/postcode-valid.directive';
import {fuseAnimations} from '../../../../@fuse/animations';
import {FuseConfigService} from '../../../../@fuse/services/config.service';
import {FuseTranslationLoaderService} from '../../../../@fuse/services/translation-loader.service';
import {CountryRegion} from '../../entity/local-db/country-region';
import {StateRegion} from '../../entity/local-db/state-region';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';


@Component({
    selector: 'register-form',
    templateUrl: './register-form.component.html',
    styleUrls: ['./register-form.component.scss'],
    animations: fuseAnimations
})
export class RegisterFormComponent implements OnInit {
    registerForm: FormGroup;
    registerFormErrors: any;
    account: any;
    countryOptions = CountryRegion.countryRegions;
    sentToInternational = false;
    stateOptions = StateRegion.AU;
    phoneRegex = '^\\+?[0-9]\\d{1,16}$'; //  '^(?:\\+?(61))? ?(?:\\((?=.*\\)))?(0?[2-57-8])\\)? ?(\\d\\d(?:[- ](?=\\d{3})|(?!\\d\\d[- ]?\\d[- ]))\\d\\d[- ]?\\d[- ]?\\d{3})$';
    suburbResult = [];
    postcodeResult = [];
    // selectedSuburbItem:Object;
    // selectedSuburbItem:Object = {
    //     suburb: "", 
    //     postcode: "", 
    //     state: ""
    // }
   
    // selectedSuburbItem:any = {
    //     suburb: "", 
    //     postcode: "", 
    //     state:  ""
    // }
    // selectedCountryItem:object[];
    selectedCountryItem:Array<any> = new Array();
    selectedSuburbItem:any;

    avoidTriggerKey = ['ArrowUp', 'ArrowLeft', 'ArrowRight', 'ArrowDown', 'Delete', 'Control', 'Alt', 'End', 'Home'];
   
    eventKey:string;
    selectedOption:string;
    subject: Subject<any> = new Subject();


    constructor(
        private fuseConfig: FuseConfigService,
        private formBuilder: FormBuilder,
        private router: ActivatedRoute,
        private route: Router,
        private registerService: RegisterService,
        private translationLoader: FuseTranslationLoaderService,
        private translate: TranslateService,
        private snackBar: MatSnackBar,
    ) {
        this.translationLoader.loadTranslations(english, chinese);
        let accountInfo: any;
        this.router.queryParams.subscribe((queryParams) => {
            accountInfo = queryParams;
            console.log(accountInfo);
            if (accountInfo === undefined) {
                this.route.navigate(['/pages/404']);
            } else {
                const accountInfo_json = JSON.parse(accountInfo.params);
                this.account = accountInfo_json;
            }
        });

        // Configure the layout
        this.fuseConfig.config = {
            layout: {
                navbar   : {
                    hidden: true
                },
                toolbar  : {
                    hidden: true
                },
                footer   : {
                    hidden: true
                },
                sidepanel: {
                    hidden: true
                }
            }
        };

        this.registerFormErrors = {
            name: {},
            companyName: {},
            ABN: {},
            phone: {},
            company_address1: {},
            company_address2: {},
            company_suburb: {},
            company_state: {},
            company_postcode: {},
            company_country: {},
        };

        
    }

    ngOnInit(): void {
        this.registerForm = this.formBuilder.group({
            name: ['', Validators.required],
            companyName: ['', Validators.required],
            // ABN: [''],
            phone: ['', [Validators.required, Validators.pattern(this.phoneRegex)]],
            company_address1: ['', [Validators.required, Validators.maxLength(39)]],
            company_address2: ['', Validators.maxLength(39)],
            company_suburb: ['', [Validators.required, Validators.maxLength(30)]],          
            company_state: ['', Validators.required],
            company_postcode: ['', [Validators.required, postcodeValidator()]],
            company_country: ['', Validators.required],
            email: [''],         
            hash: [''],
        });

        this.registerForm.valueChanges.subscribe(() => {
            this.onRegisterFormValuesChanged();
        });
       
        this.subject
        .pipe(debounceTime(600))     // input debounceTime delay
        .subscribe(() => {        
                // console.log(this.registerForm.controls['company_postcode'].value);  
                this.getSuburbPostcode();              
            }
        );
    }

    ngOnDestroy(): void
    {
        // Unsubscribe from all subscriptions
        this.subject.next();
        this.subject.complete();       
    }

    onRegisterFormValuesChanged(): void {
        for (const field in this.registerFormErrors) {
            if (!this.registerFormErrors.hasOwnProperty(field)) {
                continue;
            }
            // Clear previous errors
            this.registerFormErrors[field] = {};

            // Get the control
            const control = this.registerForm.get(field);

            if (control && control.dirty && !control.valid) {
                this.registerFormErrors[field] = control.errors;
            }
        }
    }
    selectMatch(input, options) {
        const getInput = input.trim().toUpperCase();
        for (const item of options) {
            if (getInput === item.value) {
                return item.value;
            }
            if (getInput === item.label.trim().toUpperCase()) {
                return item.value;
            }
        }
    }

    displayInternational() {
        if (this.registerForm.controls['company_country'].value === 'AU') {
            this.sentToInternational = false;
            this.registerForm.controls['company_suburb'].setValidators([Validators.required, Validators.maxLength(30)]);
            if (this.registerForm.controls['company_state'].value) {
                const stateValue = this.selectMatch(this.registerForm.controls['company_state'].value, this.stateOptions);
                this.registerForm.controls['company_state'].setValue(stateValue);
            }
            this.registerForm.controls['company_state'].setValidators([Validators.required]);
            // this.registerForm.controls['company_postcode'].setValidators([Validators.required, postcodeValidator()]);
            this.registerForm.controls['company_postcode'].setValidators([Validators.required]);

            this.registerForm.controls['company_suburb'].updateValueAndValidity();
            this.registerForm.controls['company_state'].updateValueAndValidity();
            this.registerForm.controls['company_postcode'].updateValueAndValidity();
        } else {
            this.sentToInternational = true;
            this.registerForm.controls['company_suburb'].setValidators([Validators.required]);
            this.registerForm.controls['company_state'].setValidators([Validators.required]);
            this.registerForm.controls['company_postcode'].setValidators([Validators.required]);
            this.registerForm.controls['company_suburb'].updateValueAndValidity();
            this.registerForm.controls['company_state'].updateValueAndValidity();
            this.registerForm.controls['company_postcode'].updateValueAndValidity();
        }
    }
    
    onKeydown(event, option) {
        // console.log(event.key);
        // console.log(event.timeStamp);
        this.eventKey = event.key;
        this.selectedOption = option;
        this.subject.next();  
    }
    getSuburbPostcode(){
        if (!this.sentToInternational) {    
            //clear option
            if(this.registerForm.value.company_postcode.length < 3){
                this.postcodeResult = []
            }
            if(this.registerForm.value.company_suburb === ""){
                this.suburbResult  = []
            }

            if ( this.eventKey === 'Enter' && this.registerForm.controls['company_suburb'].value.length > 3) {
                if (this.selectedOption === 'suburb') {
                    this.findSuburb();
                } else if (this.selectedOption === 'postcode') {
                    this.findPostcode();   
                }
            } else if ( this.eventKey === 'Enter' && this.registerForm.controls['company_postcode'].value.length > 3) {
                if (this.selectedOption === 'suburb') {
                    this.findSuburb();
                } else if (this.selectedOption === 'postcode') {
                    this.findPostcode();                    
                }
            } 
            else if (!this.avoidTriggerKey.includes( this.eventKey)) {
                if (this.selectedOption === 'suburb') {
                    this.findSuburb();
                } else if (this.selectedOption === 'postcode') {
                    this.findPostcode(); 
                }
            }
        }

    }
    findSuburb() {
        const data = this.registerForm.controls['company_suburb'].value;
        if (data.length >= 3) {
            this.registerService.searchSuburbPostcode({'suburb': data}).subscribe(response => {
                this.suburbResult = response.data;
            });
        }
    }  
    findPostcode() {
        const data = this.registerForm.controls['company_postcode'].value;
        if (data.length >= 3) {
            this.registerService.searchSuburbPostcode({'postcode': data}).subscribe(response => {
                // console.log(response.data)
                this.postcodeResult = response.data;
            });
        }
    }

    /**
     * @description: change country and change  Suburb/State/Postcode status
     * @param {type} 
     * @return: 
     */    
    selectCountry(option){
        // console.log(option);
        // console.log(this.selectedCountryItem);

        this.selectedCountryItem.push(option);     
        let arr = this.selectedCountryItem;      
        if(arr[arr.length-1] == arr[arr.length-2] || arr.length == 1 ){
         console.log(this.registerForm);
         return          
        }else{   
            this.registerForm.controls['company_suburb'].setValue("");
            this.registerForm.controls['company_state'].setValue("");  
            this.registerForm.controls['company_postcode'].setValue("");  

            this.registerForm.controls['company_suburb'].markAsUntouched(); 
            this.registerForm.controls['company_state'].markAsUntouched();  
            this.registerForm.controls['company_postcode'].markAsUntouched(); 
            
            // this.registerForm.controls['company_suburb'].; 
            

            this.postcodeResult = [];
            this.suburbResult = [];
        }

        //  console.log(this.registerFormErrors.company_state);
         console.log(this.registerFormErrors.company_suburb);
         console.log(this.registerForm);
        
    }

    selectSuburb(item) {
        this.selectedSuburbItem = item;
        this.registerForm.controls['company_state'].setValue(item.state);
        this.registerForm.controls['company_postcode'].setValue(item.postcode);
    }

    selectState(option){
        console.log( this.registerForm);
        // console.log(option);
        // console.log(this.selectedSuburbItem); 
        // console.log(this.selectedSuburbItem.state);  
        if(this.selectedSuburbItem == undefined){          
            return
        } else{
            if(this.selectedSuburbItem.state !== option.value){
                this.registerForm.controls['company_suburb'].setValue("");
                this.registerForm.controls['company_postcode'].setValue("");

                this.registerForm.controls['company_suburb'].markAsUntouched();               
                this.registerForm.controls['company_postcode'].markAsUntouched();            

                this.postcodeResult = [];
                this.suburbResult = [];

            }else{
                this.registerForm.controls['company_suburb'].setValue(this.selectedSuburbItem.suburb);
                this.registerForm.controls['company_postcode'].setValue(this.selectedSuburbItem.postcode);
            }

        }
        
    }

    selectPostcode(item) {      
        this.registerForm.controls['company_suburb'].setValue(item.suburb);
        this.registerForm.controls['company_state'].setValue(item.state);
    }


    submitForm(button): void {
        button.textContent = this.translate.instant('REGISTER.LOADING');
        button.disabled = true;
        if (this.account !== null && this.account !== undefined) {
            this.registerForm.controls['email'].setValue(this.account.email);  
            // this.registerForm.controls['hash'].setValue(this.account.hash);
            const data = this.registerForm.getRawValue();
            console.log(data);
            const okButton = this.translate.instant('GENERAL.GOTIT');
            this.registerService.submitRegisterForm(data).subscribe(
                (resp: any) => {
                    if (resp.messsage && resp.message === 'User does not exist') {
                        const errorNotice = this.translate.instant('REGISTER.USER-NOTEXIST');
                        this.registerService.snackNotice(errorNotice, okButton);
                        button.textContent = this.translate.instant('REGISTER.SUBMIT');
                        button.disabled = false;
                    } else if (resp.data && resp.data !== undefined && resp.data.email === this.account.email) {
                        this.route.navigate(['pages/login']);
                        const succNotice = this.translate.instant('REGISTER.FORM-SUCC');
                        this.registerService.snackNotice(succNotice, okButton);
                        button.textContent = this.translate.instant('GENERAL.SUBMIT');
                        button.disabled = false;
                    } else {
                        const faultNotice = this.translate.instant('REGISTER.FORM-ERROR');
                        this.registerService.snackNotice(faultNotice, okButton);
                    }
                    button.textContent = this.translate.instant('GENERAL.SUBMIT');
                    button.disabled = false;
                }, error => {
                    const faultNotice = this.translate.instant('REGISTER.FORM-ERROR');
                    this.registerService.snackNotice(faultNotice, okButton);
                    button.textContent = this.translate.instant('GENERAL.SUBMIT');
                    button.disabled = false;
                }
            );
        }


    }
}


function confirmPassword(control: AbstractControl): any {
    if (!control.parent || !control) {
        return;
    }

    const password = control.parent.get('password');
    const passwordConfirm = control.parent.get('passwordConfirm');

    if (!password || !passwordConfirm) {
        return;
    }

    if (passwordConfirm.value === '') {
        return;
    }

    if (password.value !== passwordConfirm.value) {
        return {
            passwordsNotMatch: true
        };
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章