我正在使用 Ionic News 应用程序。我在从服务文件获取响应时遇到一个问题。
home.page.ts
getNews(): void {
this.loading = true;
this.language = localStorage.language;
this.checkForToken();
var userId = this.loggedInUser;
this._newsService.getAllNews().subscribe(
(res: any) => {
console.log("all news==========>", res)
this.loadNewsToPage(res, userId);
},
(err) => {
this.loading = false;
this.error = err;
});
}
news.service.ts
getAllNews(){
if(this.network.type == 'none' ){
console.log(JSON.parse(localStorage.getItem("newsArray")));
this.newsArray = JSON.parse(localStorage.getItem("newsArray"))
return this.newsArray;
}else{
return this.http.get(config.baseApiUrl + 'news?isApproved=APPROVED').pipe(
map((res) => {
this.newsArray = res['data'];
localStorage.setItem('newsArray',JSON.stringify(this.newsArray))
return this.newsArray;
}),
catchError(this.handleError));
}
}
现在的问题是,当网络为“无”时,它会在服务文件中进入“if”条件并从本地存储返回响应。但当网络没有时,它会给我以下错误。
ERROR TypeError: this._newsService.getAllNews(...).subscribe is not a function
在其他条件下或存在网络时它可以正常工作。为什么会这样?
最佳答案
您的 getAllNews
函数不是 Observable。所以你不能订阅它。请参阅下面的示例,其中为第一个 if 条件和第二个 else 条件返回 Observable。您需要在每个下一个函数之后使用observer.complete()关闭Observable。
getAllNews(): Observable<any>{
return new Observable(observer => {
if(this.network.type == 'none' ){
console.log(JSON.parse(localStorage.getItem("newsArray")));
this.newsArray = JSON.parse(localStorage.getItem("newsArray"))
observer.next(this.newsArray);
observer.complete();
} else{
this.http.get(config.baseApiUrl + 'news?isApproved=APPROVED').subscribe(
(result: object) => {
this.newsArray = result['data'];
localStorage.setItem('newsArray',JSON.stringify(this.newsArray))
observer.next(this.newsArray);
observer.complete();
},
(error) => {
observer.error(error);
});
}
});
}
您现在可以访问订阅>结果中的下一个 block 以及订阅>错误中的错误 block 。
this._newsService.getAllNews().subscribe(
(res: any) => { // observer.next() brings you here
console.log("all news==========>", res)
this.loadNewsToPage(res, userId);
},
(err) => { // observer.error() brings you here
this.loading = false;
this.error = err;
});
关于javascript - 错误类型错误 : subscribe is not a function in Ionic 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58406458/