首页 文章

angular2订阅返回值

提问于
浏览
1

我在 validateUsernameIsUnique 方法中订阅了http请求服务 . 我试图根据订阅中的代码操纵 validateUsernameIsUnique() 的返回值 . 我读过一些关于异步行为的初学者文章 . 因此我知道下面的代码不起作用,因为 return ret; 未定义 . Unfortunatley我无法弄清楚如何实现我想做的事情 .

@Injectable()
export class ValidateService {

  constructor(private _authService: AuthService) { }

...

  validateUsernameIsUnique = (c: FormControl) => {

    let ret;
    if (c.value.length >= 3) {

        this._authService.uniqueUser({ username: c.value }).subscribe(data => {

          if (!data.success) {   // Username already exists       
            ret = { usernameIsTaken: true };          
          }
          else 
            ret = null;
        })

        return ret;
    }

  }

}

我订阅的Auth服务看起来像这样:

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';


@Injectable()
export class AuthService {

  authToken: any;
  user: any;

  constructor(private _http: Http) { } 

  uniqueUser(user) {

    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this._http.post('http://localhost:3000/users/username', user, { headers: headers })
      .map(res => res.json());
  }
}

Update1:

更改了注释中提到的代码

validateUsernameIsUnique = (c: FormControl) => {        
    if (c.value.length >= 3) {     
      return this._authService.uniqueUser({ username: 'zomh' }).map(res =>          
      {             
        if (!res.success) {   // Username already exists              
          return { usernameIsTaken: true };    
        }
        else
        {

          return null;
        }
      });

    }

  }

电话看起来像

ngOnInit() {        
      this.frmRegisterUser = new FormGroup({
      name: new FormControl('',[Validators.required]),
      username: new FormControl('',[Validators.required, this._validateService.validateUsernameIsUnique, Validators.minLength(3), this._validateService.validateUsernamePattern]),
      email: new FormControl('',[Validators.required, this._validateService.validateEmailPattern]),
      password: new FormControl('',[Validators.required, Validators.minLength(6)]),
      acceptTerms: new FormControl(false,[Validators.required])
    });

现在我正在收到一个看似如下的对象:
Object

抱歉,但我仍然无法在哪里找到映射的返回值,例如 { usernameIsTaken: true }

Update2 @pixelbits

它不起作用:我不知道如何调试这个?,因为在内部函数中不会出于异步原因打印console.logs . 我尝试使用已经在数据库中的用户名'zomh'(不是唯一的) .

uniqueName(): AsyncValidatorFn {
    console.log('i am here');
    return (control:AbstractControl): Promise<ValidationResult> => {

      let q = new Promise<ValidationResult>(
        (resolve, reject)=>  { 
            var name = 'zomh';
            if (name == '') {
              resolve(null);
            }
            else {

              this._authService.uniqueUser({ username: 'zomh' })
                .map(t=>t.json())
                .subscribe(response=> {
                    if (response.success === false) {

                      resolve(response);  
                    }

                      else 
                        resolve(null);

                });
            }
        });

        return q;
    }
  }

我在控制台中得到了 "i am here" ,但这就是它 . 我得到null,即使它不应该't with an existing username. I can verifiy the AuthService is working correctly ( tested it with a basic subscribe and username ' zomh') .

1 回答

  • 1

    看起来您需要将asyncronous验证器实现为工厂:

    import {  AbstractControl, AsyncValidatorFn } from '@angular/forms';
    import { Http } from '@angular/http';
    import { Injectable, Inject } from '@angular/core';
    import 'rxjs/add/operator/map';
    
    
    interface ValidationResult {
     [key:string]:boolean;
    }
    @Injectable()
    export class ValidationService {
       constructor(private _authService: AuthService)  {
    
      }
      validateUsernameIsUnique(): AsyncValidatorFn {
        return (control:AbstractControl): Promise<ValidationResult> => {
    
          let q = new Promise<ValidationResult>(
            (resolve, reject)=>  { 
                var name = control.value;
                if (name == '') {
                  resolve(null);
                }
                else {
    
                  this._authService.uniqueUser({ username: control.value })
                    //.map(t=>t.json()) // Auth Service already returning json
                    .subscribe(response=> {
                        if (response.success === false) 
                            resolve({ usernameIsTaken: true });                  
                          else 
                            resolve(null);
    
                    });
                }
            });
    
    
            return q;
        }
      }
    }
    

    确保将验证器作为第三个参数传递(这是异步验证器所在的位置,第二个参数是同步验证器)

    this.formGroup = this.fb.group( {
         'username': ['hello',, this.validationService.validateUsernameIsUnique()]
        });
    

相关问题