0

So I'm studying Angular and I'm working on a project with Spotify API. When I search for music I'm getting this error (Error trying to diff 'A$AP Twelvyy'. Only arrays and iterables are allowed). I want to use switchMap since the event triggers with keyup.

This is the service


export class SpotifyService{

    constructor(private _http: HttpClient){

    }

    searchMusic(query: string){
      debugger;
      const searchUrl=`https://api.spotify.com/v1/${query}`;



      const headers=new HttpHeaders({
        Authorization:
        "Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx"
      });

      return this._http.get(searchUrl, {headers});

    }


          getArtists(query: string) {
            debugger
            return this.searchMusic(`search?q=${query}&type=artist&limit=15`).pipe(
              switchMap(data => data["artists"].items)
            );
          }
}

This the search component

import { Component } from '@angular/core';
import {SpotifyService} from '../services/spotify.services'


@Component({
    selector: 'app-searchbar',
    templateUrl: './searchbar.component.html',
    styleUrls: ['./searchbar.component.scss'],
    providers: [SpotifyService]
})

export class SearchBarComponent {
    searchString: string;
    results: string[];
    artists: any[]=[];
    loading: boolean;
    tracks: any []=[];
    constructor(private _spotifyService:SpotifyService){
    }



          search(query){
            console.log(query);
            this._spotifyService.getArtists( query )
                  .subscribe( (data: any) => {
                    this.artists = data;
                    console.log(this.artists);
                  });
          }

}

This is the template

<div class="container">
  <input #query id="inputbar" type="text" (keyup)="search(query.value)" class="form-control" placeholder="Search...">
  <div class="search"></div>
</div>
Zoe
  • 27,060
  • 21
  • 118
  • 148

1 Answers1

0

Your error is quite simple, you are trying to iterate a string.

When you use switchMap you can handle errors using catchError inside pipe like this:

getArtists(query: string) {
  return this.searchMusic(`search?q=${query}&type=artist&limit=15`).pipe(
    switchMap(data => data["artists"].items),
    catchError(_ => of("Error!"))
  );
}

However, you will need to handle it again on your subscribe. So I'd suggest you to let your getArtists intact, and handle error in the subscribe method like this:

  this.spotifyService.getArtists('eeqw')
    .subscribe((data: any) => {
      console.log(data);
    }, (error: any) => {
      alert('Not found' + error);
  });
Jaime Yule
  • 981
  • 1
  • 11
  • 20