ray
ray

Reputation: 145

How to make ember component fetch data from server. put AJAX call inside the component seems not a good practise to handle this

An Ember Component needs to fetch data from serve, however i think put AJAX call inside the component is not a good practise.

Or use the Route to fetch data, then pass data to component.But the route's method can't share easily between different routes.

Upvotes: 3

Views: 1657

Answers (2)

Sushant
Sushant

Reputation: 1414

A component should depend only on the input that are passed to it.

If component has some internal dependency (AJAX / Other data) for input it is an anti pattern.

Ember way will be

1) Create a Route : (Get data to you application)

Sometime you dont have a route for such data (like in your case). Here you can use application route or any other parent route if have. Use the setupController to inject this data to relevant controller

2) Pass down data to component

Now your data should be a controller. Pass this data like any other to required component

{{my-comp-here data="here" ajaxData=fromRoute }}

Upvotes: 1

user663031
user663031

Reputation:

In general, you are right, it is not a good idea to put ajax calls in components. However, in a case where the data to be retrieved and displayed is intimately connected to the view--auto-completion could be one example--it should not be considered an anti-pattern.

If you think it is important to segregate the ajax call, you could consider using a {{render}} helper inside the component's template, and do the ajax work in a separate controller with an associated view where the results are displayed. Routes are not really relevant here because they are related to navigation and URLs.

Upvotes: 2

Related Questions