"Extend" all methods of a class


I import * as Foo from 'foo; a class Foo and use it in one of my services. I use a long list of methods of it that all get an options array as parameter. Now it would be useful to have these options available in my template via the returned object that I use in there. Of course I could add it to all results in my service, but I am sure I would forget it somewhere - and also this is not really the concern of the service.

So my idea is to write a wrapper class, that adds options to the result object on all methods. I then use this wrapper class instead of Foo in my service and everything is taken care of without additional code in the service.

How do I implement such a wrapper class? (Best would be if I could provide an array of method names that are then all extended and use the same logic to add the options array before calling the parent class instead of doing it for each method)

Good idea?
How do I do this?


I suppose reasonable people can disagree on this, but I vote “bad idea”. Every time I’ve tried to put this sort of logic into data container objects, especially in JavaScript which has no inherent language support for OOP, I have ended up hating the results. I suggest keeping data dumb, and putting whatever intelligence is needed into services.


But wouldn’t that mean that I have to add the same few lines in each of my service methods that use that data class?

Something like this:

function foo(bar) { 
  let options = {
    bar: bar,
    widget: 'lala',
  return this.data.method(options).then(results => { 
    result.options = options; 
    return results; 

I don’t know what “data” is here, but if it’s truly data, then what I’m saying I try to avoid is having any methods at all defined on it. All of my data containers are dumb interfaces that have only properties; no methods.


Ah ok, wrong word here then.

data is the Foo from my initial post. It is a library that gets data from a remote API. It was initially built for nodejs usage I think, but via the polyfills it works just fine in Angular. It offers the OAuth methods and a loooot of getBar() methods that I can use to get data from the server. It also checks that all parameters are there, I am using the write values for them and so on.

But unfortunately it does not return the options in the objects it returns :wink:


Does result contain a property you can use as a unique ID? If so, I’d use a Map in a provider. setOptions() sets Map<resultID, options>, and getOptions() gets the options for resultID. That way you keep your personally defined model independent from the API’s model.