我目前正在开发一个Web应用程序,该应用程序必须从SQL数据库中加载一组数据(例如某些员工或工作计划)。每当您路由到某个组件时,如果您更新数据,它将被发送到服务器并返回某种成功或错误消息。
目前,我使用的是可观察值,但它们的行为并不像我想要的那样。我订阅了一个可观察的对象,接收了我的数据并取消订阅(我也不知道要取消订阅的位置。在我的onDestroy或我的订阅的Complete
部分中?)。但是由于接收到所有导致我的应用程序失败的数据之前代码继续执行,它仍然是异步的。
这里是我的实现示例:
员工组成部分:
getEmployees(department: any){
this.employeesSub = this.employeeManagementService.getEmployees(department).subscribe(
//Sucess
data => {this.employees = data},
//Error
err => this.logger.error(err),
//Complete
() => {this.logger.log('done loading');
}
);
}
ngOnInit(){
this.selectedDepartment = this.ccs.getSelectedDepartment();
//Does the same type of request as getEmployees()
this.getDepartments();
this.paramSub = this.route.params.subscribe(
//Success
params => {
//doStuff
}
},
//Error
err => this.logger.error(err),
//Complete
() => {}
);
}
ngOnDestroy(){
this.employeesSub.unsubscribe();
this.paramSub.unsubscribe();
}
员工服务:
getEmployees(department: string): Observable<Employee[]>{
let method = "getEmployees";
let body = JSON.stringify({method, department});
this.logger.log(body);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(this.url, body, options)
.map((res:Response) =>{
this.logger.log(res.json());
return res.json();
}).catch(this.handleError);
}
我知道这可能在这里经常被问到。但是,即使我阅读了越来越多的帖子,我也仍然不确定该区别。有人可以花些时间帮助我吗?
取消订阅有点多余,因为从this._http.xxx()
返回的可观察对象在第一个事件后关闭,这导致订阅被取消。
为了确保在您的身边,您也可以使用this._http.xxx().first().subscribe(...)
。这样,无论发件人打算发出多少事件,订阅都将在第一个事件后关闭。
代码执行继续而无需等待响应是异步执行的本质,并且使用promise或observable非常相似。
如果要在数据到达后执行代码,则必须将该代码移到subscribe(...)
,map(...)
或其他可观察的运算符中。
<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9aQnRybi5qcGcifQ==” alt =“在此处输入图像描述”>可观察到的促销差异