moe*_*774 5 observable typescript angular
我正在使用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()}
);
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的那样,当组件被初始化时,它会调用两个获取数据的方法.这些方法从我的服务中获得可观察性并订阅它们.
问题是订单就像call1, call2, result1, result2, ...,我认为有些事情是不对的.它应该是call1, result1, call2, result2, ...或者我错了?我尝试在observable1中订阅observable2,onComplete但我认为专用方法将毫无用处.我已经研究并找到了一些解决方案,同时使用concat订阅了两个observable,但我只是希望代码在所有数据流量完成后继续在getDepartments()之后继续.
而且我应该在退订OnDestroy()或OnComplete在的subscribe功能我真的不明白有什么区别?
Thi*_*ier 12
如果要控制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];
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10084 次 |
| 最近记录: |