0

EDIT: The question below is a duplicate. Whilst I made my best attempts to read through other threads, I hadn't considered the scope context and so spent hours using the wrong keywords to find a resolution. I made sure to mark the helpful response once the error had been respond. My account has been blocked regardless. If admin could advice me on what more I could have done it would be greatly appreciated. I don't know what more I can add to this thread.

I am using 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))
    )

I begin with an empty options array and then within ngOnInit I call the following function:

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
              },
            );



  }

The options array is updated but the new values are not recognised by ngbTypeahead. During debugging I created an alternative array of hard-coded values (instead of an empty array) and found that those original values contiuned to show in the dom.

Clearly I have a lot to learn, but I was unable to find a similar thread explaining what I hope is a simple error...

jamesbcn
  • 307
  • 4
  • 6
  • 20

1 Answers1

2

The scope of this changes within vanilla function. Please use arrow function instead

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
              },
            );
  }
MoxxiManagarm
  • 8,735
  • 3
  • 14
  • 43