处理多个同步独立的http请求Angular 2

时间:2017-07-01 19:46:33

标签: angular http asynchronous promise observable

我正在尝试构建一个向用户显示多个图表的角度2应用程序,并且我在处理多个并行独立的http请求时面临真正的问题,当我调用超过2个请求时,我得到505响应在ngOnInit。

pass

1 个答案:

答案 0 :(得分:2)

您正在subscription内输入所有服务电话,而应该让它们独立,如下所示,

this._service.getPlant().subscribe(plants => {
    for (var i=0; i<plants.length; i++)
        for (var name in plants[i]) {
            this.plants.push(plants[i][name]);  
            console.log(plants[i][name]) ;
        }
});
this._service.getDept().subscribe(depts => {
    for (var i=0; i<depts.length; i++)
        for (var name in depts[i]) {  
            this.depts.push(depts[i][name]);
            console.log(depts[i][name])
        }
});
this._service.getMachines().subscribe(machines => {
    for (var i=0; i<machines.length; i++)
        for (var MachineName in machines[i]) {
                machines.push(machines[i][MachineName]);  
                // console.log(machines[i][MachineName]) ;
        }
 });

根据评论更新:

完成上一个

后提出另一个请求
ngOnInit(){
    this._service.getPlant().subscribe(plants => {
        for (var i=0; i<plants.length; i++)
            for (var name in plants[i]) {
                this.plants.push(plants[i][name]);  
                console.log(plants[i][name]) ;
            }
    },(error)=>{},
        ()=>{
        /////////////////////////////
        // Completion event handler
        /////////////////////////////
            this.getDepartments();
        });

    private getDepartments(){
        this._service.getDept().subscribe(depts => {
            for (var i=0; i<depts.length; i++)
                for (var name in depts[i]) {  
                    this.depts.push(depts[i][name]);
                    console.log(depts[i][name])
                }
        },(error)=>{},
        ()=>{
        /////////////////////////////
        // Completion event handler
        /////////////////////////////
            this.getMachines();
        });
    }
    private getMachines(){

        this._service.getMachines().subscribe(machines => {
            for (var i=0; i<machines.length; i++)
                for (var MachineName in machines[i]) {
                        machines.push(machines[i][MachineName]);  
                        // console.log(machines[i][MachineName]) ;
                }
         });
    }
}