使用Web API调用进行Angular 2异步自定义验证

时间:2016-10-04 00:18:32

标签: angular typescript observable

我正在尝试创建一个异步自定义验证程序,以检查注册表单中是否已存在用户名。我创建了一个服务类,它调用 Web API (如下所示)来检查唯一的用户名。

我还创建了一个异步自定义验证器,它假设调用该服务并执行验证。但是我很难理解如何将服务注入验证器。该服务还会注入 Http

任何人都知道如何正确完成此验证?

-Alan -

自定义验证器

export class UserNameValidators {
    static shouldBeUnique(control: FormControl) {
           ....
           //Need to call the Signup service here
        }
    }

服务

@Injectable()
export class SignUpService
{
        constructor(private http: Http) {

          }
shouldBeUnique(username: string): Observable<boolean> {
        let headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');
        let options = new RequestOptions({ headers: headers });

               return this.http.post('localhost/authentication/api/accounts/user/' + username, '', options)
            .map((response: Response) => {
                let result = response.toString();
                if (result === 'true')
                    return true

                return false;
            })
            .catch((error: any) => {
                if (error.status === 400) {
                    var cleandata = error._body
                        .replace(/\\n/g, "\\n")
                        .replace(/\\'/g, "\\'")
                        .replace(/\\"/g, '\\"')
                        .replace(/\\&/g, "\\&")
                        .replace(/\\r/g, "\\r")
                        .replace(/\\t/g, "\\t")
                        .replace(/\\b/g, "\\b")
                        .replace(/\\f/g, "\\f");

                    cleandata = cleandata.replace(/[\u0000-\u001F]+/g, "");

                    return Observable.throw(new Error("Unknown Error"));
                }

            });
    }
}

更新

App.Module

@NgModule({
    imports     : [BrowserModule, HomeModule, SignupModule,signupRouting, routing],
    declarations: [AppComponent],
    providers   : [AuthService, AuthGuard, SignupService],
    bootstrap   : [AppComponent]
})

自定义验证器

export class UserNameValidators {

    constructor(private service: SignupService) { }

    shouldBeUnique(control: FormControl) {
        return new Promise((resolve, reject) => {

            this.service.shouldBeUnique(control.value).subscribe(
                data => {
                    if (data.length == 0 || data.length == 1) {
                        resolve(null);
                    } else {
                        resolve({ shouldBeUnique: true });
                    }
                },
                err => {
                    resolve({ shouldBeUnique: true });
                }
            )
        });

    }
}

Signup.component

export class SignupComponent implements OnInit {
    form: FormGroup;
    signedUp: boolean = false;
    error = '';

    constructor(private fb: FormBuilder, private router: Router, private signupService: SignupService) { }

    ngOnInit() {
        this.form = this.fb.group({
            firstname: ['', Validators.required],
            lastname: ['', Validators.required],
            username: ['', Validators.compose([Validators.required, UserNameValidators.notValidEmail]), new UserNameValidators(this.signupService).shouldBeUnique],

            password: ['', Validators.compose([Validators.required, UserNameValidators.cannotContainSpace])],
            confirmpassword: ['', Validators.compose([Validators.required, UserNameValidators.cannotContainSpace])]
        }, { validator: this.matchingPasswords('password', 'confirmpassword') });
    }
}

1 个答案:

答案 0 :(得分:2)

  

但是我不知道如何将服务注入验证器

我认为那是你的问题:

您需要在app.module中注册您的服务作为提供者:

@NgModule({ 
    // imports, etc
    providers: [
    appRoutingProviders,
    SignUpService]})

使用@Injectable()装饰您的服务:

@Injectable()
export class SignUpService {
// your service...

将构造函数添加到带有SignUpService的验证器:

constructor(private signUpService: SignUpService)
{

}