Ссылка на элемент ViewChild не определена - PullRequest
0 голосов
/ 15 марта 2020

Посмотрите на код ниже.

// ...

  @ViewChild('searchBar', {static: false}) searchBar: IonSearchbar;
  @ViewChild('locations', {static: false}) locationsList: IonList;

// ...

  ngAfterViewInit() {
    this.searchBarInputSub =
      this.searchBar.ionInput
        .pipe(
          pluck('target', 'value'),
          debounceTime(400),
          distinctUntilChanged()
        ).subscribe(this.onNewLocation);
    console.log(this.locationsList);
  }

  onNewLocation(prefix: string) {
    console.log(this.locationsList);
  }

Почему onNewLocation печатает undefined? Обратите внимание, что ngAfterViewInit печатает описание объекта ...

1 Ответ

0 голосов
/ 15 марта 2020

Синтаксис неправильный, когда вы подписываетесь на наблюдаемое, также this в строке subscribe(this.onNewLocation) не относится к тому, что вы думаете.

Внесите следующее изменение:

ngAfterViewInit() {
   this.searchBarInputSub =
      this.searchBar.ionInput
        .pipe(
          pluck('target', 'value'),
          debounceTime(400),
          distinctUntilChanged()
        )
        .subscribe((location: string) => this.onNewLocation(location));
  }
...