我的角度项目中有一个名为“Animal”的打字稿基类,可以扩展到几种类型的动物。以下是一些示例代码。每个扩展类都将实现它自己的“getItems”方法,然后在promise解析后设置“isItemsLoaded”。
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;
});
}
}
我可以以某种方式附加一些代码在getItems解析后运行(如finally方法中的finally方法)吗?我想负责在基地设置“isItemsLoaded”。这样的事情可能吗?
abstract class Animal {
items: Array<...> = [];
isItemsLoaded: boolean = false;
abstract getItems(): ng.IPromise<Array<...>>.AfterResolved(this.isItemsLoaded = true;);
}
答案 0 :(得分:1)
您可以使用template method pattern。像这样:
// 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
}
}