Ng-bootstrap Typeahead problem with autocomplete?

721 Views Asked by At

I have this Angular project based on League of Legends API.

The problem is that I dont know how make the Typeahead work. It should return autocomplete values but throws an error. I'm very confused. Also, "this.champions" is not an array. If thats the problem, how can I convert it to an array?

champions.service

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class ChampionsService {

  constructor(private http: HttpClient) { }

  GetChampions(){
    return this.http.get('http://ddragon.leagueoflegends.com/cdn/10.23.1/data/es_ES/champion.json');
  }

}

HTML

<form [formGroup]="championFindForm" (ngSubmit)="SubmitFind()" novalidate>
        <div class="input-group mb-3">
            <ng-template #rt let-r="result" let-t="pro">
                <ngb-highlight [result]="r.nombre" [term]="t"></ngb-highlight>
            </ng-template>
            <input id="champions" type="text" class="form-control" formControlName="champion" [(ngModel)]="championModel"
                [ngbTypeahead]="search" [inputFormatter]="formatter" [resultFormatter]="formatter" 
                type="text" class="form-control" placeholder="Nombre de campeón" aria-label="Nombre de campeón"
                aria-describedby="basic-addon2">
            <div class="input-group-append">
                <button class="btn btn-outline-secondary" type="button">Buscar</button>
            </div>
        </div>
    </form>

.ts

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import {ChampionsService } from '../../services/champions.service';
import { debounceTime, map } from 'rxjs/operators';
import { FormControl, FormGroup, Validators } from '@angular/forms';

type genericModel = {object: string};

@Component({
  selector: 'app-champions',
  templateUrl: './champions.component.html',
  styleUrls: ['./champions.component.css']
})

export class ChampionsComponent implements OnInit {

  championFindForm: FormGroup;
  
  public champions;

  public championModel: genericModel;
  formatter = (value: genericModel) => value.object;
  
  constructor(private championsService:ChampionsService) { }

  ngOnInit(): void {
    this.championFindForm = new FormGroup({
      champion: new FormControl('', Validators.required)
    });
    this.GetAllChampions();
  }

  GetAllChampions(){
    this.championsService.GetChampions().subscribe(
      (data: any) => {
        this.champions = data.data;
        Object.keys(data.data).map((key: any, obj: any) => obj[key]);
        console.log(this.champions);
      }
    );
  }


  search = (text$: Observable<string>) =>
    text$.pipe(
      debounceTime(200),
      map(term => this.champions.filter(v => new RegExp(term, 'mi').test(v.object)).slice(0, 10))
    )

}
0

There are 0 best solutions below