我正在尝试从服务器加载部门并填充下拉列表。如果存在 routeParam (部门),我想将 formControl (部门)设置为目标项目。
嵌套的 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')));
}
})
);
}
)
);
}
答案 0 :(得分:2)
类似这样的事情应该可以解决:
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
。
答案 1 :(得分:0)
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
);