Skip to content

Instantly share code, notes, and snippets.

@thosakwe
Last active June 21, 2016 21:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thosakwe/3ca34c958dba9f43db6f60d1c3c5bf22 to your computer and use it in GitHub Desktop.
Save thosakwe/3ca34c958dba9f43db6f60d1c3c5bf22 to your computer and use it in GitHub Desktop.
Angular2 - ngOnInit after Loading Data
import {Component, OnInit} from "@angular/core";
import FooService from "foo-service.ts";
@Component({
selector: "my-elem",
templateUrl: "my-elem.html",
providers: [FooService]
})
export default class MyElemCmp implements OnInit {
data = [];
loading: true;
constructor(private _fooService:FooService) {}
ngOnInit() {
// Fetch data, then set loading to false
this._fooService.getData().then(data => {
this.data = data;
this.loading = false;
});
}
}
import {Injectable} from "@angular/core";
@Injectable()
export default class FooService {
getData = () => Promise.resolve([{hello: "world"}, {foo: "bar"}];
}
<div *ngIf="loading">
Loading, please wait...
</div>
<div *ngIf="!loading">
Data:
<ul>
<li *ngFor="#datum of data">
{{datum}}
</li>
</ul>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment