'ERROR TypeError: Cannot read property 'slice' of undefined---Typescript

how are you? I have one problem 'slice' of undefined in my project. I use autocomplete material https://material.angular.io/components/autocomplete/examples

My code.ts //get all Country from webservice

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

// Create FilterOptions

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

// filter country

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

Code.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>

Can you suggest me some idea, what is the problem?

Thank you



Solution 1:[1]

i think you're using countryes before it's defined inside subscription, i suggest to move your "Create FilterOptions" code inside allCountry subscription where countryes is defined

Solution 2:[2]

Try this...

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Fateh Mohamed
Solution 2 DV Singh