gpt4 book ai didi

angular - 如何在 Angular 2 中使用 "chain"两个单独的可观察对象

转载 作者:太空狗 更新时间:2023-10-29 17:30:51 26 4
gpt4 key购买 nike

我正在使用 Angular2 开发 Web 应用程序,但在从服务器获取数据时遇到了一些问题。

 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 同时订阅两个可观察对象的解决方案,但我只希望代码在所有数据流量完成时在 getDepartments() 之后继续。

我应该在 OnDestroy() 中取消订阅,还是在 subscribe 函数的 OnComplete 中取消订阅我真的不明白其中的区别?

最佳答案

如果你想控制 observable 的执行顺序,你需要构建一个异步数据流,利用 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];
});

关于angular - 如何在 Angular 2 中使用 "chain"两个单独的可观察对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38870195/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com