1
 export class MockedDataService {
    constructor(private Session: SessionService) {}

    private getMocked(name:string){
       return ""; // return whatever result is, will be a promise
    }


    public mocked:{
           products:{
              getAllProducts: function(){return this.getMocked("")},
              getProductByType: function(type){return this.getMocked(type)}
           }

    }
}

Now if this class is injected in a component, then you can call this service as

this.MockedDataService.mocked.products.getAllProducts().then((result) => { 
  console.log(result);
}).catch((err) => {
  console.log("error: ",err.message);        
});  

Then an error is raised: "this.getMocked is not a function" a fix for that issue is to change the code to :

getAllProducts: function(){return ()=> this.getMocked("")}

But this fix will raise another error: "this.MockedDataService.mocked.products.getAllProducts().then is not a function"

M. E.
  • 11
  • 1
  • 1
  • Also note that it is very unconventional to store methods inside of properties of a service... Why not just define getMocked on the service itself? The `then is not a function` error is because whatever you returned is not a promise. – Robin De Schepper Apr 28 '20 at 13:48

1 Answers1

1

You have lost your context afterthe getAllProducts: function(){return this.getMocked("")} assignment.

You need to use the arrow function higher on one level or bind the context explicitly

getAllProducts: () => { return this.getMocked(""); }

For shorter, just

getAllProducts: () => this.getMocked("")

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
  • that will work, but how can i pass the function parameter in getProductByType: function(type){return this.getMocked(type)} – M. E. Apr 28 '20 at 13:52
  • Pass parameter to the arrow - `getProductByType: (type) => this.getMocked(type)` – Suren Srapyan Apr 28 '20 at 13:53
  • So in the class should look like this public mocked:{ products:{ getAllProducts: ()=>this.getMocked(""), getProductByType:(type)this.getMocked(type) } } works fine – M. E. Apr 28 '20 at 14:15
  • Thank you for your help, that was fast and fine, how can I skip mocked function when call this service, I mean change this: `this.MockedDataService.mocked.products.getAllProducts()` to this: `this.MockedDataService.products.getAllProducts()` in Javascript we could export the whole object like this `return { products:{ getAllProducts: function(){return this.getMocked("")}, getProductByType: function(type){return this.getMocked(type)} }` – M. E. Apr 28 '20 at 14:21
  • Instead of the `mock` just have it's content – Suren Srapyan Apr 28 '20 at 14:27
  • I thought that would be equal to javascript return whole function, but that worked fine and thank you again, – M. E. Apr 28 '20 at 14:50
  • @M.E. If the answer helped you, can you accept it? – Suren Srapyan May 10 '20 at 07:26