javascript - Correct way to make an ajax call from EmberJs component? -
i know correct way make ajax call ember component. example
i want create reusable component makes employee search employee's id, when response comes server want update model data ajax response.
i don´t know if correct way it, i'm new on emberjs.
export default ember.component.extend({ ajax: ember.inject.service(), actions: { dosearch() { showloadingdata(); var self = this; this.get('ajax').post('http://server.ip.com/api/v1/getemployee', { "id": }).then(function(data) { self.set('model.name', data.name); self.set('model.position', data.position); hideloadingdata(); }); } }});
edit: misunderstood question, here's updated version of answer:
first, think should switch using ember-data. fetching employee id resolve calling this.get("store").find("employee", id)
.
if wish use plain ajax, suggest create service encapsulates specifics (api endpoint url, data format, , on) , exposes simple methods finding , updating models.
and finally, comply "data down, actions up" pattern, shouldn't update model in component. instead send action parent controller/component. so:
app/components/employee-selector.js
(the component you're writing):
export default ember.component.extend({ actions: { updateid(id) { ember.$.post("http://server.ip.com/api/v1/getemployee", { id: params.id }.then((response) => { this.sendaction("select", response); }); } });
app/templates/new/it-request.hbs
:
{{employee-selector select=(action "selectemployee")}}
app/controllers/new/it-request.js
:
export default ember.controller.extend({ actions: { selectemployee(employeedata) { this.set("model.name", employeedata.name); this.set("model.position", employeedata.name); } } });
old answer:
an idiomatic solution in route
.
first should add route in app/router.js
:
this.route("employees", function() { this.route("show", { path: ":id" }); }
than define route in app/employees/show/route.js
:
import ember "ember"; export default ember.route.extend({ model(params) { return new ember.rsvp.promise((resolve, reject) { ember.$.post("http://server.ip.com/api/v1/getemployee", { id: params.id }.then( (response) => { resolve(response) }, reject ); }); } });
(the reason wrapped in new promise allow response customization - replace resolve(response)
code transforms raw response server , invoke resolve
transformed version).
but if you'll have more communication api, , suppose will, suggest try using ember-data or other data layer library ember (probably orbit).
or @ least write service abstracts away communication api , use anywhere you'd use raw ajax requests.
Comments
Post a Comment