【问题标题】:ERROR TypeError: Cannot read property 'slice' of undefined---Typescript错误类型错误:无法读取未定义的属性“切片”---Typescript
【发布时间】:2018-07-18 22:26:48
【问题描述】:

你好吗? 我的项目中有一个未定义的问题“切片”。我使用自动补全材料https://material.angular.io/components/autocomplete/examples

我的代码.ts //从webservice获取所有国家

this.ws.AllCountry().subscribe(
      countryes => {
        this.countryes = countryes.map((country) => {
          return new Country(country);
        });
      }
    );

// 创建过滤器选项

   this.stateCtrl = new FormControl();
    this.filteredOptionsCountry = this.stateCtrl.valueChanges
      .pipe(
      startWith(''),
      map(country =>  country ? this.filterCountry(country) : this.countryes.slice()) // Cannot read property 'slice' of undefined
    );

// 过滤国家

 filterCountry(name: string) {
    return this.countryes.filter(country =>
      country.name.toLowerCase().indexOf(name.toLowerCase()) === 0);
  }

代码.html

 <form class="example-form">
     <mat-form-field class="example-full-width">
     <input matInput placeholder="Select Country" aria-label="State" [matAutocomplete]="auto" [formControl]="stateCtrl">
       <mat-autocomplete #auto="matAutocomplete">
         <mat-option *ngFor="let country of filteredOptionsCountry | async" [value]="country.country_id">
           {{ country.name }}
         </mat-option>
       </mat-autocomplete>
     </mat-form-field>
   </form>

你能给我一些建议吗,有什么问题?

谢谢

【问题讨论】:

标签: html angular typescript autocomplete angular-material


【解决方案1】:

我认为您在订阅中定义之前使用国家/地区,我建议将您的“创建过滤器选项”代码移动到定义国家/地区的 allCountry 订阅中

【讨论】:

  • Create FilterOptions 在构造函数中。 this.ws.AllCountry().subscribe() 在 ngOnInit() 中
【解决方案2】:

试试这个...

map((country: string | null) => country ? this._filter(country) : this.countryes.slice()));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-07
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 2021-11-22
    • 2019-06-14
    相关资源
    最近更新 更多