首页 文章

Angular2可观察与承诺

提问于
浏览
1

我目前正在开发一个Web应用程序,它必须从SQL数据库(如某些员工或工作计划)加载一组数据 . 每次当您被路由到组件时,如果您更新数据,它将被发送到服务器并返回某种成功或错误消息 .

目前我使用了observables,但它们的行为并不像我想要的那样 . 我订阅了一个observable,接收我的数据并取消订阅(我也不确定在哪里取消订阅 . 在onDestroy或我的sub的 Complete 部分?) . 但不知何故,它仍然是异步的,因为在接收导致我的应用程序失败的所有数据之前代码执行仍在继续 .

Here is an example of my implementation:

员工组成部分:

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);
}

我知道这可能经常被问到这里 . 但我真的不确定差异,即使我读了越来越多的帖子我也不会得到它 . 有人可能需要一些时间来帮助我吗?

1 回答

  • 3

    取消订阅有点多余,因为从 this._http.xxx() 返回的observable在第一个事件之后关闭,这导致订阅无论如何都被取消 .

    为确保您可以使用 this._http.xxx().first().subscribe(...) . 这样,无论发件人打算发出多少事件,订阅在第一个事件之后都会关闭 .

    代码执行继续而不等待响应是异步执行的本质,使用promise或者observable非常相似 .

    如果您希望在数据到达后执行代码,则必须将该代码移动到 subscribe(...)map(...) 或其他一些可观察的运算符 .

相关问题