ERROR TypeError:订阅不是Ionic 4中的函数

问题描述 投票:0回答:1

我正在使用Ionic News App。我在从服务文件获取响应时遇到一个问题。

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”状态,并从本地存储返回响应。但是当网络不存在时,它给我下面的错误。

错误TypeError:this._newsService.getAllNews(...)。subscribe不是功能

当它处于其他状态或存在网络时,它将正常工作。为什么会这样?

javascript ionic-framework service angular7 ionic4
1个回答
0
投票

您的getAllNews功能不是可观察的。因此,您无法订阅它。请参见下面的示例,其中您为第一个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);
        });
      }
  });
 }

您现在可以访问您的订阅中的下一个块>结果以及正在订阅中的错误块>错误。

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;
  });
© www.soinside.com 2019 - 2024. All rights reserved.