所以我正在学习 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>