• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

如何在Angular 2中“链接”两个独立的可观察对象

angular 来源:moessi774 6次浏览

我正在用Angular2开发一个Web应用程序,并且从服务器获取数据时遇到了一些问题。如何在Angular 2中“链接”两个独立的可观察对象

import ... 

@Component({ 
... 

}) 
export class EmployeeManagementTableComponent implements OnInit, OnDestroy{ 

private employees: Employee[]; 
private departments: SelectItem[] = []; 
private selectedDepartment: string; 
private columns: any[]; 
private paramSub: any; 
private employeesSub: any; 
private departmentSub: any; 


constructor(private employeeManagementService: EmployeeManagementService, 
      private route: ActivatedRoute, 
      private router: Router, 
      private ccs: ComponentCommunicatorService, 
      private logger: Logger) { } 

ngOnInit(){ 

    this.columns = [ 
    ... 
    ]; 

    //ccs is just a service for storing/getting app wide infomation 

    this.selectedDepartment = this.ccs.getSelectedDepartment(); 
    this.getDepartments(); 
    this.getEmployees(this.selectedDepartment); 

    ... 
} 

ngOnDestroy(){ 
    /*this.employeesSub.unsubscribe(); 
    this.departmentDub.unsubscribe();*/ 
} 

getDepartments(){ 

    this.departments.push({label: 'Alle', value: 'all'}); 

    this.departmentSub = this.employeeManagementService.getDepartments().subscribe(
      data => {data.forEach((item, index) => { 
         this.departments.push({label: item, value: index.toString()}); 
        });  
        }, 
      err => this.logger.error(err), 
     () => {this.logger.log('done loading'); 
       this.departmentSub.unsubscribe()} 
    ); 
} 
getEmployees(department: any){ 

this.employeesSub = this.employeeManagementService.getEmployees(department).subscribe(
      data => {this.employees = data}, 
      err => this.logger.error(err), 
     () => {this.logger.log('done loading'); 
       this.employeesSub.unsubscribe()} 
    ); 
} 

正如你看到组件初始化时它调用两个获取数据的方法。这些方法从我的服务中获得可观察的并订阅它们。
问题是,订单就像call1, call2, result1, result2, ...,我认为有不对的地方。应该是call1, result1, call2, result2, ...还是我错了?我试着在observable1的onComplete中订阅observable2,但我认为专用方法当时是无用的。 我已经研究并找到了一些解决方案,同时用concat同时订阅两个observables,但是我只希望getDepartments()在所有数据流量完成时继续执行代码。

而且我应该取消订阅OnDestroy()OnCompletesubscribe函数,我真的没有什么区别吗?

===========解决方案如下:

如果要控制可观察的执行顺序,就需要建立像flatMap(串联执行)或Observable.forkJoin(以并行执行)

下面是样本异步数据流利用操作符:

// Series 
someObservable.flatMap(result1 => { 
    return someOtherObservable; 
}).subscribe(result2 => { 
    (...) 
    (...) 
}); 

// Parallel 
Observable.forkJoin([ someObservable, someOtherObservable ]) 
    .subscribe(results => { 
    let result1 = results[0]; 
    let result2 = results[1]; 
    }); 

版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)