在 Ember 教程应用中将 ajax 请求放在哪里?
Where to put ajax request in Ember tutorial app?
我想将 "Weather: 24C" 添加到 super-rentals
tutorial app 的 rental-listing
组件。
放置此 ajax 请求的 "best-practices" 位置在哪里?
Ember.$.getJSON(`http://api.openweathermap.org/data/2.5/weather?q=${location}&APPID=${apiKey}`)
.then(function(json) {
return JSON.parse(json).main.temp;
});
我是否需要添加组件、添加模型、添加服务、添加第二个适配器、修改现有适配器?还有别的吗?所有这些?是教程使用Mirage的问题吗?我问这个是因为当我认为我接近时,我收到这样的错误:
Mirage: Your Ember app tried to GET
'http://api.openweathermap.org/data/2.5/weather?q=london&APPID=5432',
but there was no route defined to handle this request.
Define a route that matches this path in your
mirage/config.js file. Did you forget to add your namespace?
您需要配置 mirage 以允许您在 mirage 处于活动状态时拨打外部电话;我的意思是在 mirage/config.js
中使用 this.passthrough
函数,这在 api documentation 中有很好的解释。
关于你的远程调用位置的问题是;这取决于:
- 如果您需要服务器的数据到达以防路由即将打开;你应该更喜欢将它放在相应
route
. 的 model
钩子中
- 如果您打算开发一个组件,该组件将在不同的路由中重复使用,甚至在不同的应用程序中重复使用相同的远程调用;您可以考虑将 ajax 远程调用放到一个组件中。即使这通常不是很常见的情况;可能是组件本身应该被包装起来以获取数据并单独显示它以便在不同的地方重用;没有什么能阻止你这样做。然而,通常应用数据向下动作原则;通常远程调用属于路由或控制器。
- 是否使用
ember-data
model
是另一回事。如果你打算使用 ember-data
;你不应该直接使用 Ember.$.ajax
而是使用 ember-data
提供的 store
并且可能提供你的自定义 adapter/serializer 将数据转换为 ember-data
接受的格式以防万一服务器与 ember-data
接受的格式不匹配。总之;如果您像在这个问题中那样使用纯 ajax,则不需要使用 model
s。
我想将 "Weather: 24C" 添加到 super-rentals
tutorial app 的 rental-listing
组件。
放置此 ajax 请求的 "best-practices" 位置在哪里?
Ember.$.getJSON(`http://api.openweathermap.org/data/2.5/weather?q=${location}&APPID=${apiKey}`)
.then(function(json) {
return JSON.parse(json).main.temp;
});
我是否需要添加组件、添加模型、添加服务、添加第二个适配器、修改现有适配器?还有别的吗?所有这些?是教程使用Mirage的问题吗?我问这个是因为当我认为我接近时,我收到这样的错误:
Mirage: Your Ember app tried to GET
'http://api.openweathermap.org/data/2.5/weather?q=london&APPID=5432',
but there was no route defined to handle this request.
Define a route that matches this path in your
mirage/config.js file. Did you forget to add your namespace?
您需要配置 mirage 以允许您在 mirage 处于活动状态时拨打外部电话;我的意思是在 mirage/config.js
中使用 this.passthrough
函数,这在 api documentation 中有很好的解释。
关于你的远程调用位置的问题是;这取决于:
- 如果您需要服务器的数据到达以防路由即将打开;你应该更喜欢将它放在相应
route
. 的 - 如果您打算开发一个组件,该组件将在不同的路由中重复使用,甚至在不同的应用程序中重复使用相同的远程调用;您可以考虑将 ajax 远程调用放到一个组件中。即使这通常不是很常见的情况;可能是组件本身应该被包装起来以获取数据并单独显示它以便在不同的地方重用;没有什么能阻止你这样做。然而,通常应用数据向下动作原则;通常远程调用属于路由或控制器。
- 是否使用
ember-data
model
是另一回事。如果你打算使用ember-data
;你不应该直接使用Ember.$.ajax
而是使用ember-data
提供的store
并且可能提供你的自定义 adapter/serializer 将数据转换为ember-data
接受的格式以防万一服务器与ember-data
接受的格式不匹配。总之;如果您像在这个问题中那样使用纯 ajax,则不需要使用model
s。
model
钩子中