arrays - 尝试区分“...”时出错。只允许使用数组和可迭代对象。(使用 switchMap)
问题描述
所以我正在学习 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>
解决方案
您的错误很简单,您正在尝试迭代一个字符串。
当您使用 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);
});
推荐阅读
- android-room - 尝试从分页 3 寻呼机内的房间获取寻呼源时出现“无法访问主线程上的数据库”错误
- java - 更改存储在不同线程上的列表中的对象的字段
- c# - 如何在 ConfigureServices 中创建依赖于数据库上下文的实例
- google-cloud-platform - 谷歌文档人工智能
- python - python的VSCode自动完成字符串参数
- python - 无法使用 python selenium 单击电子邮件验证按钮
- android - android.util.AndroidRuntimeException:从 Activity 标志外调用 startActivity()
- python - 用最少的文档在 escpos-python 上打印繁体中文字符
- vue.js - 如何在本地存储中从具有纪元时间的项目列表中呈现格式化的日期时间
- powershell - Win10 - 如何将一个命令的输出作为另一个命令的参数来检查文件哈希?