Asynchronous Ionic-Typeerror:.then()不是函数
我尝试从爱奥尼亚的assets/data/people-data.json获取数据。在my providers/people-data.ts中Asynchronous Ionic-Typeerror:.then()不是函数,asynchronous,ionic-framework,promise,ionic2,Asynchronous,Ionic Framework,Promise,Ionic2,我尝试从爱奥尼亚的assets/data/people-data.json获取数据。在my providers/people-data.ts中 getLocalData(){ try{ this.http.get('assets/data/people-data.json').map(res => res.json()).subscribe(data => { return data; }); } catch (error) { console.log("
getLocalData(){
try{
this.http.get('assets/data/people-data.json').map(res => res.json()).subscribe(data => {
return data;
});
}
catch (error) {
console.log("Error in httprequest");
return this.data;
}
return this.data;
}
在我的search.ts页面(我需要发布数据的地方)
代码如下
generateData() {
try {
this.peopleData.getLocalData().then((result) =>{
console.log("data recieved")
});
} catch (error) {
console.error("Couldnot fetch data",error);
}
}
这是因为
getLocalData
应该返回一个Promise
,但它实际上返回的undefined
(或者无论什么This.data
在getLocalData
的开头)
下面的方法很好。在这里,
getLocalData
返回一个可观察的数据,并generateData
订阅它
getLocalData(){
return this.http.get('assets/data/people-data.json').map(res => res.json())
}
generateData(){
this.peopleData.getLocalData().subscribe(
(result) =>{
console.log("data recieved")
}, (err)=>{
console.log("Error in httprequest");
}
);
}
代码中的问题:
可观察的
和承诺
是用于处理异步代码的两种模式(其他模式为:回调
,自动等待
)
一个可见的
和承诺
,都是Javascript对象
。两者都类似于一个值的代理,该值将在稍后到达。
当值到达时(称为解析值),如果要从可观察的中提取解析值,请使用.subscribe()
,但是。如果要从承诺中提取解析值,请使用
在您的例子中,this.http.get('assets/data/people data.json')
返回一个可观察的
。另外this.http.get('assets/data/people data.json').map(res=>res.json())
返回修改后的Observable
。但是您试图使用.then()
来提取它,这是不正确的
另外,您返回的是,observable.map().subscribe()
,它不返回一个observable,而是一个subscription对象。这是初学者常见的一个难题
承诺
和可观察到的
似乎更相似。在代码中使用之前,最好在一定程度上了解它们。您的观察值和承诺是混合的。……不。请尝试仅捕获同步代码。不要将try-catch放入getLocalData
。请按原样运行我的代码。谢谢dasfdsa。它起作用了。如果您能告诉我代码中的错误,我们将不胜感激。提前感谢您编辑了解释。