ERROR TypeError: subscribe is not a function in Ionic 4

ERROR TypeError: subscribe is not a function in Ionic 4

我正在使用 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));
        }
    }

现在的问题是,当网络处于 'none' 时,它会在服务文件中进入 'if' 状态,而本地存储会做出 return 响应。但是当网络为 none.

时,它会给我以下错误

ERROR TypeError: this._newsService.getAllNews(...).subscribe is not a function

在其他情况下或存在网络时,它可以正常工作。为什么这样?

您的 getAllNews 函数不是 Observable。所以你不能订阅它。请参阅下面的示例,其中您 return 一个 Observable 用于第一个 if 条件和第二个 else 条件。您需要在每个下一个函数之后使用 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;
  });