【问题标题】:Element reference of ViewChild is undefinedViewChild 的元素引用未定义
【发布时间】:2020-03-16 01:20:53
【问题描述】:

看看下面的代码。

// ...

  @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 会打印对象描述...

【问题讨论】:

  • 我认为您没有正确使用订阅语法。你可以试试:).subscribe(() => this.onNewLocation());
  • 如果我打印 prefix 它可以工作。
  • @NicholasK 你是对的。我将订阅语法更改为.subscribe((location: string) => this.onNewLocation(location)); 问题是OnNewLocation 中的this 指针类型,它指向与订阅者相关的对象。
  • @NicholasK Fine :)

标签: angular viewchild


【解决方案1】:

订阅 observable 时语法不正确,subscribe(this.onNewLocation) 行中的 this 也不是您认为的。

进行以下更改:

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

【讨论】:

    猜你喜欢
    • 2022-08-20
    • 2022-07-19
    • 1970-01-01
    • 2019-10-29
    • 2020-05-04
    • 2019-03-15
    • 2017-03-11
    • 2023-03-21
    • 2019-10-03
    相关资源
    最近更新 更多