简体   繁体   English

Angular / RxJS-嵌套可观察-重构语​​句

[英]Angular/RxJS - Nested Observable - Refactor Statement

I'm attempting to load departments from the server and populate a dropdown. 我正在尝试从服务器加载部门并填充下拉列表。 If there's a routeParam (dep) present, I'd like to set the formControl (department) to the targeted item. 如果存在routeParam (dep),我想将formControl (部门)设置为目标项目。

The nested pipe statements seems a bit off to me, but I'm still relatively new to RxJS. 嵌套的管道语句对我来说似乎有点离谱,但对于RxJS来说我还是一个相对较新的人。 Is there a better way to write the assignment statement for department$ ? 有没有更好的方法来编写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')));
              }
            })
          );
        }
      )
    );
}

Something like this should do the trick: 这样的事情应该可以解决问题:

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

Might try combineLatest instead of withLatestFrom as well. 也可以尝试用combineLatest代替withLatestFrom

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM