Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

angular - Typeahead options not displaying

I need an assistance on this code i am currently writing, i am getting data from a remote service which i did successfully as it shows in the log, the problem now is the typeahead doesn't show options upon clicking. kindly assist.

i have consulted blogs and other stackoverflow questions relating it but no results.

Below are my code

TS

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
  providers: [HomeServiceService]
})
export class HomeComponent implements OnInit {
   title = 'Autocomplete Example in Angular 6';

  

   searchTerm: FormControl = new FormControl();
   myDestination = <any>[];

   constructor (private service: HomeServiceService){

   }


   


  ngOnInit(): void {

    this.searchTerm.valueChanges.subscribe(
      term => {
        if ( term != ''){
          this.service.search(term).subscribe(
            data => {
              this.myDestination = data as any[];
              console.log(this.myDestination)
            
            }
          )
        }

        
      }
    )

service.ts

@Injectable()
export class HomeServiceService {

  constructor(private httpClient : HttpClient) { }

  search(term){

    var listOfBooks = this.httpClient.get('http://192.168.88.250:8080/api/v1/searchterminals/?searchTerm=' + term)
    .pipe(
      debounceTime(500),
      map(
        (data: any) => {
          return (
            data.length != 0 ? data as any[] : [{"BookName" : "No Record Found"} as any]
          );
        }
      )
    )
    return listOfBooks;
  }
  

html

 <mat-form-field class="container" >

          <input type="text" placeholder="Search destination ..."
                matInput 
                [formControl]="searchTerm" 
                [matAutocomplete]="auto">  
  
  
                <mat-autocomplete #auto="matAutocomplete">
  
                  <mat-option *ngFor="let destination of this.myDestination.name" [value]="destination.name">
                      
                      {{ destination.name}}
                      {{ destination.city.name}}
                      
                  </mat-option>

                </mat-autocomplete>
  
      </mat-form-field>
question from:https://stackoverflow.com/questions/65884292/typeahead-options-not-displaying

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have noticed three problems.

  1. In your .HTML, your *ngFor loop is wrong.
    You're iterating over this.myDestination.name, which doesn't exist on the array "myDestination" and is not a property of the Array class. Remove the '.name' from your *ngFor loop to iterate successfully. In the comments, you mentioned other errors, this could be related your second line in the loop where you are accessing destination.city.name which is accessing .name of undefined.

Based on your service.TS file, your array would have the structure [{BookName: string}]. To visualise it, you can write it out: const myDestination = [{"BookName" : "No Record Found"}], which if you play around with your IDE in the TS, it will help you with understanding that neither .name exists on the array as a property, and neither is it set as a variable on any of the items in the array:

enter image description here

And neither does it exist on iterated items: enter image description here

Which leads into the second problem I noticed:
2. In your .HTML, you're asking Angular to print out the value destination.city.name, which doesn't exist, either: enter image description here

  1. In your home.component.ts, at declaration you're casting myDestination to type any, which confuses the IDE to guide you that it is indeed an array. Instead, write this: myDestination: Array<any> = []. Read more about casting here and Type Assertion here.

When you write your code out like this, it will help you understand that Angular is only as capable as the JavaScript (Typescript) you give it. Have a look in the official documentation to learn more.

Some highly opinionated jargon:

  • Naming of arrays should be plural - myDestinations
  • Don't use type any unless absolutely necessary.
  • Using plugins like Angular Language Service (or alike for your IDE) will assist you to detect these problems sooner.
  • DebounceTime should be used before calling a service (or at least, before calling the API) and not on the response.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...