【问题标题】:Angular/RxJS - Nested Observable - Refactor StatementAngular/RxJS - 嵌套 Observable - 重构语句
【发布时间】:2019-04-17 18:21:38
【问题描述】:

我正在尝试从服务器加载部门并填充下拉列表。如果存在 routeParam (dep),我想将 formControl (department) 设置为目标项目。

嵌套的 pipe 语句对我来说似乎有点不对劲,但我对 RxJS 还是比较陌生。有没有更好的方法来为department$编写赋值语句?

public form: FormGroup;
public departments$: Observable<Department[]>;

constructor(
  private route: ActivatedRoute,
  private departmentService: DepartmentService) {}

get department() {
   return this.form.get('department') as FormControl;
}

ngOnInit() {
    this.form = new FormGroup({
      department: new FormControl('', Validators.required)
    });

    this.departments$ = this.route.paramMap.pipe(
      switchMap(
        (params: ParamMap) => {
          return this.departmentService.getDepartments().pipe(
            tap(departments => {
              if (params.has('dep') && departments && departments.length) {
                this.department.setValue(departments.find(dep => dep.id === +params.get('dep')));
              }
            })
          );
        }
      )
    );
}

【问题讨论】:

  • 逻辑对我来说看起来没问题,如果它不符合if 语句只需要重置控制

标签: angular rxjs


【解决方案1】:

这样的事情应该可以解决问题:

this.departments$ = this.route.paramMap.pipe(
  withLatestFrom(this.departmentService.getDepartments()),
  filter(([params, departments]) => {
    return params.has('dep') && departments.length
  }),
  tap(([params, departments]) => {
    this.department.setValue(
      departments.find(dep => dep.id === +params.get('dep'))
    );
  })
)

也可以试试combineLatest 而不是withLatestFrom。

【讨论】:

  • 从未想过使用带有LatestFrom 运算符的#rxjs 和返回Observable 的函数调用:-O Cool!
【解决方案2】:
this.departments$ = this.route.paramMap.pipe(
  map(params => params.get('dep')),
  switchMap(dep => this.departmentService.getDepartment(dep))
  // The find department logic belongs in the service
);

【讨论】:

    猜你喜欢
    • 2017-03-03
    • 1970-01-01
    • 2021-11-02
    • 2020-01-02
    • 2019-07-16
    • 1970-01-01
    • 2015-11-13
    • 2013-07-03
    相关资源
    最近更新 更多