Last active
May 1, 2017 10:32
-
-
Save tomastrajan/03bb62b66e480a644352e9818c6f8b6a to your computer and use it in GitHub Desktop.
Angular Model Pattern - component state subscription
This file contains 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
@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