|
@ -1,48 +1,37 @@ |
|
|
import { Component } from '@angular/core'; |
|
|
|
|
|
|
|
|
import { Component, OnDestroy, OnInit } from '@angular/core'; |
|
|
import { |
|
|
import { |
|
|
AbstractControl, |
|
|
AbstractControl, |
|
|
FormBuilder, |
|
|
FormBuilder, |
|
|
FormControl, |
|
|
FormControl, |
|
|
ValidationErrors, |
|
|
ValidationErrors, |
|
|
} from '@angular/forms'; |
|
|
} from '@angular/forms'; |
|
|
import { Observable, of } from 'rxjs'; |
|
|
|
|
|
import { map } from 'rxjs/operators'; |
|
|
|
|
|
|
|
|
import { Observable, of, Subject, takeUntil } from 'rxjs'; |
|
|
|
|
|
import { debounce, debounceTime, distinctUntilChanged, filter, map } from 'rxjs/operators'; |
|
|
|
|
|
|
|
|
import { UserService } from './user.service'; |
|
|
|
|
|
|
|
|
|
|
|
@Component({ |
|
|
@Component({ |
|
|
selector: 'my-app', |
|
|
selector: 'my-app', |
|
|
templateUrl: './app.component.html', |
|
|
templateUrl: './app.component.html', |
|
|
styleUrls: ['./app.component.css'], |
|
|
styleUrls: ['./app.component.css'], |
|
|
}) |
|
|
}) |
|
|
export class AppComponent { |
|
|
|
|
|
readonly form = this.fb.group({ |
|
|
|
|
|
id: this.fb.control('', { |
|
|
|
|
|
asyncValidators: [this.shouldBeExists], |
|
|
|
|
|
updateOn: 'blur', |
|
|
|
|
|
}), |
|
|
|
|
|
password: this.fb.control(''), |
|
|
|
|
|
|
|
|
export class AppComponent implements OnInit, OnDestroy { |
|
|
|
|
|
readonly condition = new FormControl(); |
|
|
|
|
|
readonly stop$=new Subject<void>(); |
|
|
|
|
|
ngOnInit():void{ |
|
|
|
|
|
this.condition.valueChanges |
|
|
|
|
|
.pipe( |
|
|
|
|
|
debounceTime(500), |
|
|
|
|
|
filter((condition:string)=> !!condition), |
|
|
|
|
|
distinctUntilChanged(), |
|
|
|
|
|
takeUntil(this.stop$) |
|
|
|
|
|
) |
|
|
|
|
|
.subscribe({ |
|
|
|
|
|
next:(condition) =>console.log(`查詢條件:${condition}`), |
|
|
}); |
|
|
}); |
|
|
|
|
|
|
|
|
get id(): FormControl { |
|
|
|
|
|
return this.form.get('id') as FormControl; |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
constructor(private fb: FormBuilder, private userSerivce: UserService) {} |
|
|
|
|
|
|
|
|
|
|
|
shouldBeExists( |
|
|
|
|
|
control: AbstractControl |
|
|
|
|
|
): Observable<ValidationErrors | null> { |
|
|
|
|
|
if ( |
|
|
|
|
|
control.value === undefined || |
|
|
|
|
|
control.value === null || |
|
|
|
|
|
control.value === '' |
|
|
|
|
|
) { |
|
|
|
|
|
return of(null); |
|
|
|
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
return this.userSerivce |
|
|
|
|
|
.isExists(control.value) |
|
|
|
|
|
.pipe(map((isExists) => (isExists ? null : { shouldBeExists: true }))); |
|
|
|
|
|
|
|
|
ngOnDestroy():void{ |
|
|
|
|
|
this.stop$.next(); |
|
|
|
|
|
this.stop$.complete(); |
|
|
} |
|
|
} |
|
|
} |
|
|
} |