Skip to content

Instantly share code, notes, and snippets.

@bermanboris
Last active December 18, 2017 20:13
Show Gist options
  • Save bermanboris/b74af38a63e1c716748dc614d373f94d to your computer and use it in GitHub Desktop.
Save bermanboris/b74af38a63e1c716748dc614d373f94d to your computer and use it in GitHub Desktop.
Angular Dynamic Properties Decorator
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
function getData(url) {
return function (target, key) {
const privateKey = `_${key}`
function getter() {
if (this[privateKey]) {
return this[privateKey];
}
this[privateKey] = this.http.get(`https://jsonplaceholder.typicode.com${url}`);
return this[privateKey]
}
function setter(newVal) {
if (this[privateKey] !== newVal) {
this[privateKey] = newVal;
}
}
Object.defineProperty(target, key, {
get: getter,
set: setter,
enumerable: true,
configurable: true
})
}
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
@getData('/users') users;
constructor(private http: HttpClient) {
}
}
<div *ngFor="let user of users | async">{{ user.name }}</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment