【问题标题】:Unable to access the members which are instantiated in one method in another method in Angular无法访问在 Angular 的另一种方法中以一种方法实例化的成员
【发布时间】:2018-11-21 19:18:12
【问题描述】:

我能够将 displayFn() 函数中 user.id 的数据存储到 sourceId 中并在控制台中打印,但是当我尝试在 onClick() 中访问它时,即使 displayFn() 是调用它在控制台中显示未定义。如果这是个愚蠢的问题,请不要介意。下面是我的组件代码。提前致谢。

import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';
import { DataService } from '../data.service';
import { Router } from '@angular/router'
import { Global } from './Global'
import { LocationsService } from '../locations.service';

export class Locations {
  id: string;
  value: string;
}
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  loc: Locations[] = [];
  sourceId: number;
  destinationId: number;
  myControl1 = new FormControl();
  myControl = new FormControl();
  filteredOptions1: Observable<Locations[]>;
  filteredOptions: Observable<Locations[]>;

  constructor(private router: Router, private locations: LocationsService) {}

  ngOnInit() {

    this.locations.getLocations().subscribe(
      data => {
        for (var i = 0; data[i] != null; i++) {
          this.loc.push(data[i]);
        }
      },
      error => {
        console.log("error in receiving data");
      },
    );

    this.filteredOptions = this.myControl.valueChanges
      .pipe(
        startWith<string | Locations>(''),
        map(value => typeof value === 'string' ? value : value.value),
        map(name => name ? this._filter(name) : this.loc.slice())
      );

    this.filteredOptions1 = this.myControl1.valueChanges
      .pipe(
        startWith<string | Locations>(''),
        map(value => typeof value === 'string' ? value : value.value),
        map(name => name ? this._filter1(name) : this.loc.slice())

      );
  }

  displayFn(user: Locations): string {

    this.sourceId = parseInt(user.id);
    console.log("sourceId = " + this.sourceId);
    return user.value;
  }

  private _filter(name: string): Locations[] {

    const filterValue = name.toLowerCase();
    return this.loc.filter(option => option.value.toLowerCase().indexOf(filterValue) === 0);
  }

  public displayFn1(user: Locations): string {

    this.destinationId = parseInt(user.id);
    console.log("destinationId = " + this.destinationId);
    return user.value;
  }

  private _filter1(name1: string): Locations[] {
    const filterValue1 = name1.toLowerCase();
    return this.loc.filter(option1 => option1.value.toLowerCase().indexOf(filterValue1) === 0);
  }

  onClick() {

    console.log("from onclick, sourceID = " + this.sourceId);
    console.log("from onclick, sourceID = " + this.destinationId);
    this.router.navigate(['/services', this.sourceId,this. destinationId]);
  }
}

下面是我使用 Angular 材料自动完成表单的 HTML。

<form>
<input type="text" placeholder="To" matInput [formControl]="myControl" [matAutocomplete]="auto" id="toPlaceName"
                  class="ajxPlaceCs ui-autocomplete-input">
                <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
                  <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
                    {{option.value}}
                  </mat-option>
                </mat-autocomplete>

                <input type="text" placeholder="From" matInput [formControl]="myControl1" [matAutocomplete]="auto1" id="fromPlaceName"
                  class="ajxPlaceCs ui-autocomplete-input">
                <mat-autocomplete #auto1="matAutocomplete" [displayWith]="displayFn1">
                  <mat-option *ngFor="let option1 of filteredOptions1 | async" [value]="option1">
                    {{option1.value}}
                  </mat-option>
                </mat-autocomplete>
<input type="button" name="searchBtn" (click)="onClick()" id="searchBtn" class="chkavailabilityBtn"
                  value="Check Availability" title="Search">
</form>

【问题讨论】:

    标签: javascript angular typescript


    【解决方案1】:

    尝试将您的 [displayWith]="displayFn" 更新为 [displayWith]="displayFn.bind(this)"

    您可以check here了解更多信息。

    【讨论】:

    • 谢谢,这就是答案,其实我还有另一种愚蠢的做法,但你的答案是完美的。
    • 如果您的问题可以通过答案解决,您可以接受答案。
    • 我做到了,但投票的最低声望是 15,我有 11。无论如何,谢谢。
    • 你不能投票,但你已经提出了问题,你可以接受答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多