相关文章推荐
听话的硬盘  ·  android.database.sqlit ...·  1 年前    · 
温柔的牛肉面  ·  RecyclerView源码剖析: ...·  1 年前    · 
鼻子大的苹果  ·  memory - Error in ...·  1 年前    · 
成熟的单杠  ·  javascript - ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

So, my issue is I am trying to build a custom validator on Angular 15, and I get an error message that tells this:

"Type 'Observable<{ titleAlreadyExists: boolean; } | null>' is not assignable to type 'Observable'. Type '{ titleAlreadyExists: boolean; } | null' is not assignable to type 'ValidationErrors'. Type 'null' is not assignable to type 'ValidationErrors'."

This is my validator:

  alreadyExistingTitle(alreadyExistingTitles: String[]): AsyncValidatorFn {
    return (control: AbstractControl): Observable<ValidationErrors> => {
      return of(alreadyExistingTitles.includes(control.value))
        .pipe(
          map((result: boolean) =>
            result ? { titleAlreadyExists: true } : null
                what if you change it to: result ? { titleAlreadyExists: true } :  { titleAlreadyExists: false }; ?
– Rick
                Jan 30 at 23:48
                Well, from what I understand from this official source (angular.io/guide/form-validation#defining-custom-validators), the validator "takes an Angular control object and returns either null if the control value is valid or a validation error object."
– Tamsin-chan
                Jan 30 at 23:55

Modify the return type from Observable<ValidationErrors> to Observable<ValidationErrors | null>.

alreadyExistingTitle(alreadyExistingTitles: String[]): AsyncValidatorFn {
  return (control: AbstractControl): Observable<ValidationErrors | null> => {
    return of(alreadyExistingTitles.includes(control.value)).pipe(
      map((result: boolean) => (result ? { titleAlreadyExists: true } : null))
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.