Angularjs Services使用多组件视图上的Observable实现

时间:2017-10-24 20:29:13

标签: angular rxjs angular-services behaviorsubject

目前我在Angular实施Observables方面遇到了麻烦,该服务将被各种组件使用。我有一个问题,基本上我在组件C(Tab样式)中有组件A和组件B.组件A是创建一个对象,让我们说轮子和组件B用于创建一个使用下拉菜单从组件A中选择哪个轮子的汽车。我的问题是当我创建一个轮子时,我必须刷新新创建的轮子的页面出现在组件B的下拉列表中,这就是我尝试实施Observables的原因,但到目前为止我还没有成功。

服务:

constructor(private http: Http) {
    this._departamentos = <BehaviorSubject<Departamento[]>>new BehaviorSubject([]);
    this.departamentos = this._departamentos.asObservable();
  }

    private url: string = 'http://localhost:8080/';
  departamentos: Observable<Departamento[]>;
  private _departamentos: BehaviorSubject<any[]>;

    // <------------------------ GET ------------------------>
    getDepartments(): Observable<Departamento[]>{
        this.departamentos = this.http.get(this.url+'selectdepartamentos')
          .map(this.extractData)
          .catch(this.handleError);
    return this.departamentos;
  }

  private extractData(response: Response) {
      let body = response.json();
      return body || {};
  }

  private handleError(error: Response) {
      console.log(error);
      return Observable.throw(error.json().error || "500 internal server error");
  }

  // <------------------------ ADD ------------------------>
  addDepartment(newDepartment){
    return this.http.post(this.url + 'departamento', newDepartment).map(
      response => this._departamentos.next(Object.assign({}, newDepartment)) );
  }

    // <------------------------ UPDATE ------------------------>
    updateDepartment(nameOldDepartment, newDepartment){
        return this.http.put(this.url+'update/'+nameOldDepartment+'/departamento', newDepartment);
    }

    // <------------------------ DELETE ------------------------>
    deleteDepartment(nameOldDepartment){
        return this.http.delete(this.url+'delete/'+nameOldDepartment);
    }

订阅组件:

this.departamentoService.getDepartments()
  .subscribe( departments => this.arregloDepartamentos = departments,
              error => this.errorMessage = <any>error);

值得一提的是,当我刷新页面时,我最初可以从我的组件B中获取值,但即使我在我的Add方法(在服务中)上有observable的下一个函数,当我添加时没有任何反应即使该对象插入DB。

非常感谢任何帮助,提前谢谢。

2 个答案:

答案 0 :(得分:0)

如果您希望添加的项目在添加后立即显示,则可以尝试

this.departamentoService.addDepartment(newDept).switchMap(()=>this.getDepartments())
 .subscribe( departments => this.arregloDepartamentos = departments,
          error => this.errorMessage = <any>error);

答案 1 :(得分:0)

这是我结束实施的方式:

服务:

private departmentsSubject = new BehaviorSubject([]);
private departments: Departamento[];

// <------------------------ GET ------------------------>
getDepartments(): Observable<Departamento[]>{
    return this.departmentsSubject.asObservable();
}
private extractData(response: Response) {
  let body = response.json();
  return body || {};
}
private handleError(error: Response) {
  console.log(error);
  return Observable.throw(error.json().error || "500 internal server error");
}
loadDepartments(){
   var sub = this.http.get(this.url+'selectdepartamentos')
      .map(this.extractData)
      .catch(this.handleError);
  sub.subscribe(
     data => this.departments = data,
     err => console.log(err),
     () => this.refresh()
  );
}
private refresh() {
   this.departmentsSubject.next(this.departments);
}

Component.ts:

this.departamentoService.getDepartments().subscribe(
  departments => this.arregloDepartamentosDelete = departments
);
this.departamentoService.loadDepartments();