Home > Mobile >  Type checking with an array in Typescript
Type checking with an array in Typescript

Time:05-10

I'm attempting to call the api = https://pokeapi.co/api/v2/type

I wish to display the array in the data using the async pipe.

I'm doing this via the html:

<option *ngFor="let pokemonType of pokemonTypes$ | async" [value]="pokemonType.url">{{pokemonType.name | titlecase}}</option>

I have a Filter interface for this:

export interface Filter {
  name: string;
  url: string;
}

I have the following method in my httpService file:

getTypes(): Observable<Filter[]> {
        return this.http.get<Filter[]>("https://pokeapi.co/api/v2/type", { responseType: 'json', observe: 'response' }).pipe(map((res: any) => res.body.results));
    }

But when I try to set pokemonTypes$ in my component:

pokemonTypes$: Filter[] = [];
this.pokemonTypes$ = this.httpService.getTypes();

I get the following error:

Type 'Observable<Filter[]>' is missing the following properties from type 'Filter[]': length, pop, push, concat, and 27 more

Any ideas as to why?

CodePudding user response:

pokemonTypes$ is expected to be an observable, yet your'e initializing it as an empty list.

if you want to init it with empty list, you should init it as an observable which contains empty list like this:

pokemonTypes$ = of([]) as Observable<Filter[]>;
  • Related