NuNn DaDdY
NuNn DaDdY

Reputation: 2992

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.

The nested pipe statements seems a bit off to me, but I'm still relatively new to RxJS. Is there a better way to write the assignment statement for 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')));
              }
            })
          );
        }
      )
    );
}

Upvotes: 0

Views: 103

Answers (2)

Adrian Brand
Adrian Brand

Reputation: 21638

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

Upvotes: 0

Phix
Phix

Reputation: 9900

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.

Upvotes: 2

Related Questions