2017-07-09 8 views
0

Imはデータベースから与えられた電子メールが存在するかどうかを確認する目的から、入力フィールドのキー変更を検出し、非常に新しく角度をつけて反応する。キー交換で観測可能な要求を実行しています

コード:

checkIfExists(email: string){ 
    this.emailToSearch.next(email); 
    } 

emailExists: Observable<boolean>; 
    private emailToSearch = new Subject<string>(); 
    private user = new RegistrationUser(null, null, null, null, null); 

    ngOnInit(): void { 
    this.emailExists = this.emailToSearch 
     .debounceTime(500) 
     .distinctUntilChanged() 
     .switchMap(
     email => this.registrationService.exists(email)); 

    } 


    <input type="text" class="form-control" name="email" (keyup)="checkIfExists(email.value)" #email="ngModel" required [(ngModel)]="user.email"> 
+0

提供された回答で十分です。頑張って。 –

答えて

1

あなたのコードは、これまでのところ大丈夫のようです。あなたが不足している唯一のものは、実際にsubscribeメソッドを呼び出すことによって、サブスクリプションを呼び出すことである:一つのことがあり

ngOnInit(): void { 
    this.emailExists = this.emailToSearch 
     .debounceTime(500) 
     .distinctUntilChanged() 
     .switchMap(
     email => this.registrationService.exists(email)) 
     .subscribe((result) => doSomething(result)); 
    } 

あなたと注意する必要があります。あなたの場合、何らかの理由でthis.registrationService.existsから受け取ったObservableがエラーになると、検索が中断されます。

ngOnInit(): void { 
    this.emailExists = this.emailToSearch 
     .debounceTime(500) 
     .distinctUntilChanged() 
     .switchMap(
     email => this.registrationService.exists(email).catch(() => Observable.empty())) 
     .subscribe((result) => doSomething(result)); 
    } 

空いている観測情報は、あなたのサブスクリプションをアクティブのままにします。

関連する問題