简体   繁体   English

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

[英]How to call array of multiple async methods in Angular using Rxjs?

I have the Base Validator method which has list of ivalidator . 我有具有ivalidator列表的Base Validator方法。

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 ???
        }

    }
}

Each validator method exposes the validate() method which returns an observable. 每个validator方法都公开validate()方法,该方法返回一个可观察值。

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

ValidatorModel is ValidatorModel是

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

My question is : 我的问题是:

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 ??? 我如何遍历所有验证器并一个接一个地调用其ASYNC方法,并在出现错误时中断并返回?

If you want the your validations to be executed one by one, use the merge operator: 如果要一次一次执行验证,请使用merge运算符:

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

If you want your validations to be executed parallel at the same time, use the forkJoin operator: 如果希望同时并行执行验证,请使用forkJoin运算符:

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

As for error handling, both merge and forkJoin will throw the error whenever they encounter them, and you can handle it at your subscribe() handler. 至于错误处理, mergeforkJoin都会在遇到错误时抛出错误,您可以在您的forkJoin subscribe()处理程序中进行处理。 If you are doing (pipe) more operations to the Observable<ValidatorModel> , then the error will be thrown up the final stack: 如果您要对Observable<ValidatorModel>做更多的操作,那么错误将被抛出最终的堆栈:

someValidator.subscribe(
            (results) => {
            },
            (error) => {
                //handle error here
            },
            () => {
                //observable completed
            })

If you choose to explicitly handle the error in your base class, then use the catch operator: 如果选择显式处理基类中的错误,请使用catch运算符:

return Observable.forkJoin(obs)
    .catch(error=>{
        console.log('error encountered',error);
        //handle your errors here
        //Return an empty Observable to terminate the stream
        return Observable.empty();
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM