Search code examples
angularionic-frameworkrxjsionic4

.subscribe method is returning undefined in ionic


The method in my webservice class return data but when I try to access the data by .subscribe method in my component it returns undefined.

The code of method in my service class. I am getting data in this method. And I can see it using 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);
      }
    )
  );
 }

The code in my component class, I am getting undefined here in console.log:

recoverData() {

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

       

If someone knows what is the problem then please let me know.


Solution

  • If you're aren't using the map operator to transform the notification, you could use tap operator instead. It also accepts the error callback like you're attempting to do. In contrast, the map operator does not accept the error callback function, so the error logs won't be printed.

    Try the following

    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);
          }
        )
      );
    }
    

    The tap only performs side-effects (like the console logs here) and doesn't require any value to be returned.