我正在尝试在我正在构建的 Ionic 3 应用程序中使用 Spotify api 获取数据,但由于某种原因,当我尝试 console.log 数据时,它显示为未定义。让我展示一些代码,然后进一步解释。这是我的 getData():
getData(){
console.log("getData has been called!!!");
return this.http.get(this.dataUrl).map((res) => {
res.json(),
console.log(res.json())//this works fine
});
}
上面的代码工作正常。它位于名为“soundData”的提供商/服务中。问题出在下面的代码上。当我尝试 console.log 数据时,它在我的浏览器中显示为未定义:
ionViewDidLoad(){
this.soundData.getData().subscribe(
returnedData=> {
this.data = returnedData;
console.log(this.data) //this shows as undefined
},
returnedError => {
this.error = returnedError;
});
}
我真的不明白我做错了什么。看起来一切都应该工作正常,但也许我错过了一些东西,因为我是 TypeScript 和 Ionic 的新手。
最佳答案
您需要从.map
返回
getData() {
console.log("getData has been called!!!");
return this.http.get(this.dataUrl).map((res) => {
console.log(res.json());//this works fine
return res.json();
});
}
更惯用的方法是使用 .do
方法单独执行日志记录操作,如下所示
getData() {
return this.http.get(this.dataUrl)
.map(res => res.json())
.do(json => console.log(json));
}
关于javascript - 在 Ionic3 中订阅提供程序后,Console.log 显示为未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43568348/