我在某些API上使用fetch获取数据,看起来像这样。
并且我正在获取此数据(如您所见),我正在使用一个诺言,这里是代码
数据源
const baseUrl = "https://api.musixmatch.com/ws/1.1";
const apiKey = "78fa4727ab9c4495d4fc07dae75f775b";
const chartTrackPopular = "chart.tracks.get?
chart_name=top&page=1&page_size=5&country=jp&f_has_lyrics=1";
const chartTrackAll = "chart.tracks.get?chart_name=top&page=1&page_size=5&country=us&f_has_lyrics=1";
class DataSource {
// initialize the data
static getPopularLirik(){
return fetch(`${baseUrl}/${chartTrackPopular}&apikey=${apiKey}`)
.then(response => {
return response.json();
})
.then(responseJson => {
if(responseJson.message.body.track_list) {
return Promise.resolve(responseJson.message.body.track_list);
} else {
return Promise.reject(`error`)
}
})
.catch(error => {
console.log(error);
})
}
}
export default DataSource;
我得到数据,但是当我尝试循环它时,我无法获得数据。这是我要获取数据的方式
popular-list.js
import './popular-item.js'
class PopularList extends HTMLElement {
constructor(){
super();
this.shadowDOM = this.attachShadow({mode: "open"});
}
set items(item){
this._item = item;
this.render();
}
render(){
this.shadowDOM.innerHTML = "";
this._item.forEach(musicitem => {
const itemElements = document.createElement("popular-item");
itemElements.items = musicitem;
// this.shadowDOM.appendChild(itemElements);
})
// let result = DataSource.getPopularLirik();
// console.log(this._item.track);
}
};
customElements.define("popular-list", PopularList);
这是我得到的错误
VM55555 popular-list.js:20 Uncaught TypeError: this._item.forEach is not a function
at HTMLElement.render (VM55555 popular-list.js:20)
at HTMLElement.set items [as items] (VM55555 popular-list.js:15)
at renderResult (VM55554 main.js:13)
at HTMLDocument.main (VM55554 main.js:19
我不知道怎么以及为什么会发生这种情况,我想如果我尝试循环数据我就可以得到值,但我什至不能做到。我该如何解决?