.subscribe 方法在 ionic 中返回 undefined

.subscribe method is returning undefined in ionic

我的网络服务中的方法 class return data 但是当我尝试在 component 中通过 .subscribe 方法访问 data 时 returns 未定义.

我的服务中的方法代码class我正在用这种方法获取数据。我可以 使用 console.log.

查看它
getData() {
return this.networkService
  .getRequest("clienti/v1/session")
  .pipe(
    map(
      (data) => {
        console.log("getData");
        console.log(JSON.stringify(data));
       
          return data;
        }
      },
      (error) => {
        console.log("getData error");
        console.log(error);
      }
    )
  );
 }

我的组件class中的代码,我在console.log中未定义:

recoverData() {

this.dataService.getData().subscribe(
  (data) => {
    console.log("data");
    console.log(data);
  },
  (error) => {
    console.log(error);
  }
);
}

       

如果有人知道问题出在哪里,请告诉我。

如果您不使用 map 运算符转换通知,您可以使用 tap operator instead. It also accepts the error callback like you're attempting to do. In contrast, the map 运算符 接受错误回调函数,因此不会打印错误日志。

尝试以下方法

getData() {
  return this.networkService.getRequest("clienti/v1/session").pipe(
    tap(
      (data) => {
        console.log("getData");
        console.log(JSON.stringify(data));
      },
      (error) => {
        console.log("getData error");
        console.log(error);
      }
    )
  );
}

tap 仅执行 side-effects(如此处的控制台日志)并且不需要返回任何值。