2

I have an Angular component which pulls data from the server to populate a dropdown and pulls a parameter from the route to set the selected option in the dropdown. This is all done in ngOnInit(). Because both of these use observables, is my solution going to have a race condition where the dropdown selected value can be set before the options are populated?

import { Component, OnInit } from '@angular/core';
import { AbstractControl, FormBuilder, FormGroup, NgForm } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { ToastrService } from 'ngx-toastr';

import { ProjectService } from '../../shared/services/project.service';

@Component({
    selector: 'app-project-status-form',
    templateUrl: './project-status-form.component.html',
    styleUrls: ['./project-status-form.component.scss']
})
export class ProjectStatusFormComponent implements OnInit {

    projectShortName: string;
    projectsShortName: string[];
    projectStatusForm: FormGroup;

    constructor(
        private fb: FormBuilder,
        private projectService: ProjectService,
        private route: ActivatedRoute,
        private toastr: ToastrService
    ) {
        this.projectStatusForm = this.fb.group({
            projectShortName: '',
            statusText: '',
            varianceOriginal: ''
        });
    }

    ngOnInit(): void {
        // Populate dropdown.
        this.projectService.getProjectsShortName().subscribe((data) => this.projectsShortName = data);

        // Set the selected value of the dropdown.
        this.route.params.subscribe(params => {
            this.projectShortName = params['projectShortName'];
            const projectShortNameDropdownBox: AbstractControl = this.projectStatusForm.get('projectShortName');

            if (this.projectShortName) {
                projectShortNameDropdownBox.setValue(this.projectShortName);
                projectShortNameDropdownBox.disable();
            } else {
                projectShortNameDropdownBox.enable();
            }
        });
    }
}
<form #npsForm="ngForm" class="col-md-8" [formGroup]="projectStatusForm">
    <div class="form-group">
        <label for="projectShortName">Project</label>
        <select id="projectShortName" class="form-control" formControlName="projectShortName" required>
            <option *ngFor="let shortName of projectsShortName" [value]="shortName">{{shortName}}</option>
        </select>
    </div>
    <div class="form-group">
        <label for="statusText">Status Text</label>
        <textarea id="statusText" class="form-control" formControlName="statusText" required rows="4"></textarea>
    </div>
    <div class="form-group">
        <label for="varianceOriginal">Variance</label>
        <input id="varianceOriginal" class="form-control" formControlName="varianceOriginal" required type="text">
    </div>
</form>
Trisped
  • 5,705
  • 2
  • 45
  • 58

2 Answers2

2

It can be a race condition. Usually, pulling data from API takes more time than router but i would still prefer to use mergeMap to avoid race condition errors. You can check below link for sample mergeMap code:

https://jsfiddle.net/btroncone/41awjgda/

//emit 'Hello'
const source = Rx.Observable.of('Hello');
//map to inner observable and flatten
const example = source.mergeMap(val => Rx.Observable.of(`${val} World!`));
//output: 'Hello World!'
const subscribe = example.subscribe(val => console.log(val));
Learning
  • 1,333
  • 16
  • 24
  • I ended up using switchMap instead of mergeMap so it will automatically unsubscribe if `getProjectsShortName()` returns multiple times. – Trisped Sep 21 '18 at 20:38
0

Multiple async operations without explicit synchronization is always a race condition. The likelihood of a race condition in this case is low---since one operation involves IO, while the other does not---but your implementation cannot guarantee order.

You can explicitly synchronize by using flatMap(). Also, if your component isn't a routed feature module, consider using a route snapshot instead; it is synchronous.

Rafael
  • 7,605
  • 13
  • 31
  • 46