Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 5组合或重构多个订阅调用_Angular_Rxjs_Angular5 - Fatal编程技术网

Angular 5组合或重构多个订阅调用

Angular 5组合或重构多个订阅调用,angular,rxjs,angular5,Angular,Rxjs,Angular5,我正在我的web项目中使用Angular 5.2。在其中一个页面中,我对不同的webAPI方法使用了多个subscribe调用。虽然它们是不同的,但独立的调用也带来了不同的数据集 但是我在想,有没有一种方法可以用一种语法将Subscribe调用组合在一起,使代码看起来小巧整洁 ngOnInit(): void { this._documentService.getTypes() .subscribe(px => { this._docTyp

我正在我的web项目中使用Angular 5.2。在其中一个页面中,我对不同的webAPI方法使用了多个subscribe调用。虽然它们是不同的,但独立的调用也带来了不同的数据集

但是我在想,有没有一种方法可以用一种语法将Subscribe调用组合在一起,使代码看起来小巧整洁

ngOnInit(): void {

    this._documentService.getTypes()
        .subscribe(px => {
            this._docTypeList = px;
        },

        error => {
           console.log("Grid Err:: " + error.message);
        }
        );


    this._documentService.getCategories()
        .subscribe(rx => {
            this._catList = rx;               
        },
        error => {
            console.log("Grid Err:: " + error.message);  }
        );
}
有没有办法重构这段代码使其简短


请建议

使用
forkJoin
组合多个观察值

forkJoin(this._documentService.getTypes(), this._documentService.getCategories() ) 
    .subscribe(rx => {
        this._docTypeList = rx[0] 
        this._catList = rx[1];               
    },
    error => {
        console.log("Grid Err:: " + error.message);  }
    );

让我快速尝试一下。forkJoin会同时进行多个API调用吗?是的。它将一次发送多个调用,并在订阅Nice Sachila:-)之前等待所有响应。比方说,如果我必须单独进行错误处理的话。我们可以使用这种语法吗?当它们加入时会发生什么?例如,如果一个有错误,那么另一个会发生什么?