如何解决单击按钮并从输入文本中获取新值后更新模型挂钩值
新人来了,
async model() {
let response = await fetch('http://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid=[APIKeyPlaceholder]);
var data = await response.json();
return data;
}
我正在使用 openweathermap api 来获取当前天气数据并在 api 中传递城市参数。
我正在获取此 data
值并将其显示在 .hbs
文件中。现在我添加了一个输入文本字段和用于输入城市名称的按钮。如何使用我从 .hbs
文件中获取的新值更新城市名称和模型挂钩值(即更新数据值从 api fetch 命令返回)?
我使用控制器吗?如何将输入绑定到 ember 变量?
解决方法
我建议您在 URL 中保留城市。这将允许用户为特定城市添加书签并共享视图。此外,它还允许您配置路由以在查询参数的值发生变化时自动重新运行模型挂钩。
- 注册一个查询参数。这目前需要一个控制器:
import Controller from '@ember/controller'; export default class ArticlesController extends Controller { queryParams = ['city']; }
- 在路由的
model
钩子中使用查询参数。它作为作为第一个参数传入的 params 对象的一部分传递。async model({ city }) { let response = await fetch( `http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=[APIKeyPlaceholder]` ); const data = await response.json(); return data; }
- 配置路由以在
model
查询参数的值发生更改时重新运行city
钩子:import Route from '@ember/routing/route'; export default class ArticlesRoute extends Route { queryParams = { city: { refreshModel: true } }; }
- 通过触发转换来更新
city
查询参数。我正在使用一个组件来说明这一点。但同样的方法适用于控制器、路由甚至服务,因为它只依赖于transitionTo
method of theRouterService
。import Component from '@glimmer/component'; import { inject as service } from '@ember/service'; export default class MyComponent extends Component { @service router; @action changeCity(city) { // This update query parameters of the current route. // If you want to redirect to another route,you can // pass the route and optional models as additional // arguments _before_ the options object. this.router.transitionTo({ queryParams: { city }}); } }
请在 Ember.js 官方指南的 Query Parameter chapter 中找到更多详细信息和解释。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。