Skip to content

Instantly share code, notes, and snippets.

@tomastrajan
Last active May 1, 2017 10:32
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 tomastrajan/03bb62b66e480a644352e9818c6f8b6a to your computer and use it in GitHub Desktop.
Save tomastrajan/03bb62b66e480a644352e9818c6f8b6a to your computer and use it in GitHub Desktop.
Angular Model Pattern - component state subscription
@Component({
selector: 'todos',
template: `
<!--
accessing multiple properties,
we're better off subscribing only once in component's ngOnInit()
-->
Done todos: {{count.done}}
Remaining todos: {{count.remaining}}
All todos: {{count.all}}
<ul>
<!-- implicit subscription using | async pipe -->
<li *ngFor="let todo of todosService.todos$ | async;">
{{todo.name}}
</li>
</ul>
`
})
export class TodosComponent implements OnInit, OnDestroy {
subscription: Subscription;
counts: TodosCounts;
constructor(public todosService: TodosService) { }
ngOnInit() {
// explicit subscription using .subscribe()
this.subscription = this.todosService.todosCounts$
.subscribe(counts => (this.counts = counts)));
}
ngOnDestroy() {
subscription.unsubscribe();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment