Decorators are a powerful feature of TypeScript that allow for efficient and readable abstractions when used correctly. In this lesson we will look at how we can use decorators to initialize properties of a class to promises that will make GET requests to certain URLs. We will also look at chaining multiple decorators to create powerful and versatile abstractions.

function Get(url) {
return function (target: any, name: string) {
// For future chain or cache on the same 'name'
const hiddenInstanceKey = "_$$" + name + "$$_";
const init = () => {
return fetch(url).then(response => response.json());
}; Object.defineProperty(target, name, {
get: function () {
return init();
},
configurable: true
});
}
} function First(num) {
return function(target: any, name: string) {
const hiddenInstanceKey = "_$$" + name + "$$_";
// access prvious getter on 'name'
const prevInit = Object.getOwnPropertyDescriptor(target, name).get;
const init = () => {
return prevInit()
.then(response => (response as any[]).slice(, num));
}; Object.defineProperty(target, name, {
get: function() {
return this[hiddenInstanceKey] || (this[hiddenInstanceKey] = init());
},
configurable: true
});
}
} class TodoService {
// Decorators runs from bottom to top
@First()
@Get('https://jsonplaceholder.typicode.com/todos')
todos: Promise<any[]>;
} const todoService = new TodoService();
todoService.todos.then(todos => {
console.log(todos);
})

最新文章

  1. soj杂题
  2. ime-mode
  3. Inversions
  4. iOS AR技术初体验,使用EasyAR示例程序的小白指南
  5. .NET+Oracle 分页
  6. mysql远程连接
  7. 微信小程序 app.json 配置
  8. winform动态的文字效果
  9. 适配器模式(Adpater Pattern)
  10. JavaScript浏览器解析原理
  11. ORM-面向对象&amp;关系数据库
  12. Codeforces Round #521 (Div. 3)
  13. 修改Linux服务器的ttl值
  14. jvm 线上命令
  15. swoole深入学习 1. swoole初始
  16. rabbitmq级联之shovel插件和exchange.bind
  17. GitHub C 和 C++ 开源库的清单(含示例代码)
  18. 线性回归,多项式回归(P2)
  19. [转载] java的书
  20. 做更好的自己 ——读《我是IT小小鸟》有感

热门文章

  1. Maven介绍---POM、Dependency Management、Coordinates
  2. JS:body元素对象的clientWidth、offsetWidth、scrollWidth、clientLeft、offsetLeft、scrollLeft
  3. docker从零开始网络(七) 配置daemon和容器
  4. win上安装Redis并将其设置为服务
  5. 2014年spark开发者大赛火热进行中!
  6. Python:文件操作技巧(File operation)(转)
  7. HDU 2551 竹青遍野(循环,水)
  8. struts2 action 字段问题
  9. [POJ 1739] Tony&#39;s Tour
  10. POJ 2115 C Looooops(Exgcd)