title: Angular Reactive Forms Async Validation using an Observable from Service
body: <p>I'm doing a web application in Angular 8.3.4. I have a form using Reactive Forms and I want to add Async Validation to make sure that the name entered is unique. I have read a lot of examples out there, but for some reason is not working for me.</p>
  
  <p>Service</p>
  
  <pre><code>export class BrandService {
    brands: Observable&lt;BrandId[]&gt;;
  }
  </code></pre>
  
  <p>Component</p>
  
  <pre><code>export class CreateNewComponent {
  
    form: FormGroup;
  
    constructor(
      private formBuilder: FormBuilder,
      private brandService: BrandService
    ) {
      // Creates a form group
      this.form = this.formBuilder.group({
        name: ['', Validators.compose([
          Validators.required,
          Validators.minLength(6),
          CustomValidator.unique(this.brandService.brands)
        ])]
      });
    }
  }
  </code></pre>
  
  <p>Custom validator</p>
  
  <pre><code>export class CustomValidator {
  
    static unique(brands: Observable&lt;BrandId[]&gt;) {
      return (control: AbstractControl) =&gt; {
  
        const name = control.value.toLowerCase();
  
        return brands.pipe(
          map(items =&gt; items.filter(b =&gt; b.name.toLowerCase() === name)),
          map(items =&gt; items.length ? {unique: false} : null)
        );
  
      };
    }
  
  }
  </code></pre>
  
  <p>I'm passing the Observable of the service from the component to the CustomValidator. Right now, the control has: <code>status: "INVALID"</code></p>
  
  <p>By the way, what should I explicitly return in my <code>unique</code> method?</p>
  
  <p>My goal is to know if the name already exists in the array of the Observable to return a control error.</p>