尝试差异'...'时出错。只允许数组和迭代。 (使用switchMap)

问题描述 投票:0回答:1

所以我正在研究Angular,我正在开发一个使用Spotify API的项目。当我搜索音乐时,我收到此错误(错误尝试区分'A $ AP Twelvyy'。只允许数组和迭代)。我想使用switchMap,因为事件触发了keyup。这是代码。提前致谢。

这是服务


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

这是搜索组件

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

}

这是模板

<div class="container">
  <input #query id="inputbar" type="text" (keyup)="search(query.value)" class="form-control" placeholder="Search...">
  <div class="search"></div>
</div>
arrays angular subscribe switchmap
1个回答
0
投票

您的错误非常简单,您正在尝试迭代字符串。

当您使用switchMap时,您可以使用管道内的catchError来处理错误,如下所示:

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

但是,您需要在订阅时再次处理它。所以我建议你让你的getArtists完好无损,并在订阅方法中处理错误,如下所示:

  this.spotifyService.getArtists('eeqw')
    .subscribe((data: any) => {
      console.log(data);
    }, (error: any) => {
      alert('Not found' + error);
  });
© www.soinside.com 2019 - 2024. All rights reserved.