如何使用Rxjs在Angular中调用多个异步方法的数组?

时间:2018-08-21 03:16:06

标签: angular typescript asynchronous rxjs

我有一个Base Validator方法,其中有ivalidator列表。

import { IValidator, ValidatorModel } from "../validation/ivalidator";
import { Observable } from "rxjs/Observable";

export abstract class BaseValidator implements IValidator {

    private validators = new Array<IValidator>();

    //Validators are pushed to the base validator =>Not implemented yet

    validate(): Observable<ValidatorModel> {

        for (let i = 0; i < this.validators.length; i++) {
            //How do I loop thru all the validator and call its ASYNC method 
            //one by one and break and return when there is an error ???
        }

    }
}

每个validator方法都公开validate()方法,该方法返回一个可观察值。

export interface IValidator {
    validate(): Observable<ValidatorModel>;
}

ValidatorModel是

export class ValidatorModel {
    readonly isSuccessful: boolean;
    errors: Array<string>;
}

我的问题是:

如何遍历所有验证器并调用其ASYNC方法     出现错误时,一个接一个地打破并返回???

1 个答案:

答案 0 :(得分:1)

如果要一次一次执行验证,请使用merge运算符:

class Survey(models.Model):
    history = HistoricalRecords()
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                             related_name='surveys',
                             on_delete=models.CASCADE)

    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    is_completed = models.BooleanField(default=False)

    def __str__(self):
        return self.is_completed

如果您希望同时并行执行验证,请使用forkJoin运算符:

validate(): Observable<ValidatorModel> {
    let obs = this.validators.map(validator=>validator.validate());
    return Observable.merge(obs);
}

对于错误处理,validate(): Observable<ValidatorModel> { let obs = this.validators.map(validator=>validator.validate()); return Observable.forkJoin(obs); } merge都会在遇到错误时抛出错误,您可以在forkJoin处理程序中进行处理。如果您要对subscribe()进行更多操作,那么错误将被抛出最终堆栈:

Observable<ValidatorModel>

如果您选择显式处理基类中的错误,请使用someValidator.subscribe( (results) => { }, (error) => { //handle error here }, () => { //observable completed }) 运算符:

catch