Last active
December 18, 2017 20:13
-
-
Save bermanboris/b74af38a63e1c716748dc614d373f94d to your computer and use it in GitHub Desktop.
Angular Dynamic Properties Decorator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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