javascript - "this"在 map 运算符 Angular 中未定义

标签 javascript angular typescript rxjs ngrx

我正在尝试为 Slug 表单控件创建自定义验证器。 这是我的代码。

ngOnInit() {
    this.slugCtrl.setAsyncValidators(this.slugValidator);
}

slugValidator(control: AbstractControl) {
    const obs1 = control.valueChanges.pipe(
      debounceTime(300),
      distinctUntilChanged(),
      map(val => {
        this.isError = of(false);
        if (val === ' ') {
          this.isAvailable = of(false);
          // this.slugCtrl.setErrors({ required: true });
          return { required: true };
          // obs.next({ required: true });
          // obs.complete();
        }
        this.isAvailable = of(false);
        if (this.slugCtrl.valid) {
          this.store.dispatch(new SlugActions.checkSlug({ slug: val }));
        }

        console.log(val);
      })
    );

    return obs1;
}

当验证器运行时,它会说无法读取未定义的属性 isError。这意味着“this”没有在 map 函数中传递。 我在这里做错了什么?

此外, 如何返回多个可观察值?因为我的 slug 验证需要从不同的资源检查很多内容,并且每个资源都会返回一个可观察值。 这是进一步的代码

   this.store.select(getSlugsIsProcessingFail()).subscribe(data => {
    this.store.select(getSlugsIsProcessingError()).subscribe(_err => {
      if (_err === 'Server error') {
        alert(
          'There was an error processing your request. Please try again!'
        );
        this.isError = of(false);
      } else if (_err.hasOwnProperty('message')) {
        this.error = _err.message;
        // this.slugCtrl.setErrors({ available: true });

        this.isError = of(true);
        return { required: true };

      }
    });
    this.store.select(getSlugsIsProcessingSuccess()).subscribe(data => {
      if (data) {
        this.isAvailable = of(true);
        // this.slugCtrl.setErrors(null);
         return null;

      }
    });
  });

最佳答案

您应该使用箭头函数将其与您的函数绑定(bind)

slugValidator = (control: AbstractControl) => {
...

}

关于javascript - "this"在 map 运算符 Angular 中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52041751/

相关文章:

使用 Firestore 进行排序、分页和过滤的 Angular Material 数据表

typescript - TSLint : Property 'params' does not exist on type 'NavigationState'

node.js - 为什么在使用 Typescript 时不需要 Node 的类型定义?

webstorm 10.0.2 中的 typescript 1.5 beta,出现错误 : TS2304-Cannot find name 'DataView'

javascript - return true 实际上返回 undefined

javascript - Google Apps 脚本将日期插入 GSheets 但更改为未定义

javascript - 每次我再次运行时,动画变得越来越快

JavaScript 单选按钮和显示

node.js - 使用 Angular、express 和 multer 发布图像和文本

angular - 根据提供的json动态生成多个 Canvas 区域