Answer the question
In order to leave comments, you need to log in
Render variables from a service?
Here one question appeared, which probably relates more to the best practices of Angular 2.
Let's say we have a service that makes a request to the server and receives an array of something in response. Would it be considered correct to render a service variable onto a view and leave the component itself untouched?
In the component:
constructor(
publick service: myService
){}
<div>
<span *ngFor="let user of service.users">{{user.name}}</span>
</div>
Answer the question
In order to leave comments, you need to log in
From the point of view of "best practices" this is, of course, a bad idea, because such a solution is poorly tested and prone to bugs. Let's say you decide to change something in the service. Then it is very likely that your entire application will fall apart if you use this variable, say, not only in this component, but also in several more.
The best solution would certainly be to provide an interface to the service. In the described version, probably getUsers(), which will return a ready-made array, Promise or Observable, depending on the need. And the internal kitchen and, in particular, variables, it is better to hide from users.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question