首页 > 解决方案 > RxJS Map 无法识别更新的数组值

问题描述

编辑:下面的问题是重复的。虽然我尽最大努力阅读其他线程,但我没有考虑范围上下文,因此花了几个小时使用错误的关键字来找到解决方案。一旦错误得到响应,我确保标记有用的响应。无论如何,我的帐户已被阻止。如果管理员可以就我可以做的更多工作提出建议,我将不胜感激。我不知道我还能在这个线程中添加什么。

我正在使用 ng-bootstrap ngbTypeahead:

HTML:

<input id="typeahead-config"
               class="form-control" 
               [ngbTypeahead]="search" 
               name="muni"
               [(ngModel)]="filter.muni"
               required/>

TS:

    text$.pipe(
      debounceTime(200),
      distinctUntilChanged(),
      map(term => term.length < 2 ? []
        : this.options.filter(v => v.toLowerCase().startsWith(term.toLocaleLowerCase())).splice(0, 10))
    )

我从一个空选项数组开始,然后在 ngOnInit 中调用以下函数:

public getMunicipalities(){
    return this.httpClient
            .get(
              'http://localhost:8080/api/municipalities'
            )
            .pipe(map((data: any) => data.map(e => e = e.name)))
            .subscribe(
              function (xhr) {
                this.options =  xhr;
                console.log(this.options);
              },
              function (err) {
                  // Log the error
              },
            );



  }

选项数组已更新,但 ngbTypeahead 无法识别新值。在调试期间,我创建了一个硬编码值的替代数组(而不是一个空数组),并发现这些原始值继续显示在 dom 中。

显然我有很多东西要学,但我找不到类似的线程来解释我希望是一个简单的错误......

标签: angularrxjs

解决方案


thisvanilla 函数的变化范围。请改用箭头功能

public getMunicipalities(){
    return this.httpClient
            .get(
              'http://localhost:8080/api/municipalities'
            )
            .pipe(map((data: any) => data.map(e => e = e.name)))
            .subscribe(
              (xhr) => {
                this.options =  xhr;
                console.log(this.options);
              },
              (err) => {
                  // Log the error
              },
            );
  }

推荐阅读