Issue
I was wondering if using a service method in a template was an anti-pattern in Angular6 :
By instance
component.ts
constructor(public myService: MyService) {}
component.html
<div>{{myService.getItems() | async}}</div>
Solution
Yes it is. You should be assigning the observable returned from the method to a property in your component and then use it in your template.
myObservable$;
constructor(private myService: MyService) {}
ngOnInit() {
this.myObservable$ = this.myService.getItems();
}
And in your template:
<div>{{myObservable$ | async}}</div>
REASON(S)
There are several reasons for doing this.
- This implementation has a better separation of concerns. It hides the implementation logic from the template. The template should only need to know about the Observable. It doesn't need to know things like where exactly did the Component get this value from. Which Service's which method did it call to get this observable?
- It promotes a pattern that can be better Unit Tested. You won't be able to do this if you're calling the service's method in your template.
Answered By - SiddAjmera
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.