Pass and return value from Ionic Services

Hello,

in Ionic TypeScript application, I’m trying to create class functions functionality to send value from page to services, set and get result, return it to home page :

In home.page.ts I have variable value, I want set this value from home.page.ts with data.service.ts and get it back in home.page.ts to display in html {{value}}:

  export class HomePage {
      value: any;

I’m passing numeric values with var value = this.myService(1, 3) function:

  getTextData() {
    this.value = this.myService(1, 0);
  }

from home.page.ts:

  async myService(item, set) {
    this.value = await this.dataService.returnData(item, set);  
    this.console(this.value);  
    return this.value;
  }

to data.service.ts which successfully shows result from console, but does not returns value to home.page.ts. this.console(this.value); from home.page.ts returns [object Promise] from data.service.ts, whereconsole.log(item+'\n'+set); shows received values from home.page.ts:

  returnData(item, set) {  
    this.serviceFunction(item, set);
    console.log(item+'\n'+set);
  }

and console.log(this.result); from following serviceFunction(item, set) function, which result wants to be attached to home.page.ts this.value:

serviceFunction(item, set) {
   this.result = response[item].title[set];
   console.log(this.result);
}

It seems like, I’m using something completely wrong, because I’m only sending parameters with request function in data.service.ts without set of variable in data.service.ts.

I’ve tried inside the return Promise.resolve:

 returnData(item, set) {
    return Promise.resolve(
       this.serviceFunction(item, set)
    );
  }

return after serviceFunction:

 returnData(item, set) {
    this.serviceFunction(item, set);
    return this.result;
 }

and set before Promise.resolve:

 returnData(item, set) {
    this.serviceFunction(item, set);
    return Promise.resolve(this.result);
 }

or:

 returnData(item, set): Promise<any> {
     return this.serviceFunction(item, set);
 }

and from home.page.ts:

myService(item, set) {
    this.dataService.returnData(item, set)
    .then(data => {
        var result = data;
        console.log(result);
    });
  }

In this case Property .then does not exist on type void.:

“Asynchronous” programming in JavaScript is not very intuitive, because the language lacks support for concurrency (which is why I put it in quotes). When you are starting out, I think it’s best to avoid async / await entirely, because they obscure what is happening. Two things I think should be avoided as much as possible by everybody are the explicit Promise construction antipattern and any. any completely defangs TypeScript’s ability to provide you targeted error messages that tell you exactly what’s wrong with your code.

I would recommend emulating the code style of chapter 4 of the Tour of Heroes, which covers interacting with services.