Rob Rob - 6 months ago 7
AngularJS Question

Is it possible to run some code after an abstract extended method runs in typescript?

I have a typescript base class in my angular project called "Animal" that is extended for several types of animals. Here is some sample code to illustrate. Each extended class will implement it's own "getItems" method and then set "isItemsLoaded" after the promise resolves.

abstract class Animal {

items: Array<...> = [];
isItemsLoaded: boolean = false;
abstract getItems(): ng.IPromise<Array<...>>;
}

class Hippo extends Animal {
getItems() {
//return a promise to get a list of hippos
return this
.getHippos(...)
.then(list, => {
...
this.isItemsLoaded= true;
});
}
}

class Tiger extends Animal {
getItems() {
//return a promise to get a list of tigers
return this
.getTigers(...)
.then(list, => {
...
this.isItemsLoaded= true;
});
}
}


Can I somehow attach some code to run after the getItems resolves (like a finally method) in the Animal base class? I would like to be responsible for setting "isItemsLoaded" in the base. Is something like this possible?

abstract class Animal {

items: Array<...> = [];
isItemsLoaded: boolean = false;
abstract getItems(): ng.IPromise<Array<...>>.AfterResolved(this.isItemsLoaded = true;);
}

Answer

You can use template method pattern. Something like this:

// stripped down code for simplicity
abstract class Animal {
    isItemsLoaded = false;
    protected abstract getItemsForAnimal(): ng.IPromise<Array<...>>;

    getItems() {
        const items = this.getItemsForAnimal();
        this.isItemsLoaded = true;
        return items;
    }
}

class Hippo extends Animal {
    protected getItemsForAnimal() {
        // return a promise to get a list of hippos
    }
}
Comments