【问题标题】:How to pass http.call results to a template?如何将 http.call 结果传递给模板?
【发布时间】:2018-04-28 17:31:09
【问题描述】:

我的client/main.js 有以下代码:

Template.hello.onCreated(function helloOnCreated() {
  // counter starts at 0
  this.counter = new ReactiveVar(0);
  var token = Meteor._localStorage.getItem("token");
  var result = HTTP.call('GET', 'http://faa22147.ngrok.io/auth/users', {
    headers: {
      "Content-type": "application/json",
      'Authorization': "Bearer " + token
    }
  }, function (error, result) {
    if (!error) {
      console.log(result.data);
      this.users = result.data;
    }
    console.log(error.response.content);
  });
});

result.data 具有从 API 正确返回的对象。

模板很简单,但是响应没有返回给模板。

<template name="hello">
  <button class="btn btn-primary">Click Me</button>
  <p>You've pressed the button {{counter}} times.</p>
  {{#each users}}
    {{>user}}
  {{/each}}

</template>

<template name="user">
  {{name}}  
</template>

【问题讨论】:

  • this.users 也设为反应变量。
  • 关于this 以及是否可以从模板上下文访问users 或者是否需要帮助器也存在不确定性。
  • 我尝试让 this.users 反应,并尝试使用助手,从启动器 users() 复制 counter() 示例 { return Template.instance().users.get(); },然后使用:instance.users=result.data;没有任何工作仍然
  • 你需要set()它到result.data,假设它是一个数组,而不是用数组覆盖它。 this.uesrs.set(result.data).
  • 你可以使用箭头函数来摆脱对bind的需要。

标签: javascript meteor meteor-blaze


【解决方案1】:

模板助手在reactive computation is invalidated 时重新运行。

ReactiveVar 是一个响应式数据源,在其上调用get() 会创建一个reactive dependency。当这在模板助手的上下文中完成时,它会创建一个响应式计算来监听其依赖项的失效。

当您将 set() 值设置为其他值时会发生这种失效,这会导致帮助程序重新运行并更新模板。

Template.hello.onCreated(function() {
  this.users = new ReactiveVar(null); // (1) initialize to null, so that we can tell when loading
  const token = Meteor._localStorage.getItem("token");

  HTTP.call('GET', 'http://faa22147.ngrok.io/auth/users', {
    headers:{
      "Content-type": "application/json",
      "Authorization": `Bearer ${token}`,
    }}, (e, r) => {
      if (!e) {
        this.users.set(r.data); // (2) set the reactive var to trigger a reactive computation
      }
      // todo: handle error case
    });
});

Template.hello.helpers({
  users() {
    return Template.instance().users.get(); // supplies the reactive variable to the template
  },
});

我为users 尚未设置的情况添加了loading... 文本。当users helper 无效(设置为数组)时,它会重新运行,users 现在是真实的,内部each 被触发。

请注意,这不处理error 的情况,因此如果HTTP 调用失败,它会卡在loading...

<template name="hello">
  {{#if users}}
    {{#each users}}
      {{>user}}
    {{/each}}
  {{else}}
    loading...
  {{/if}}
</template>

【讨论】:

    猜你喜欢
    • 2011-07-10
    • 2018-09-03
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    • 2023-04-04
    • 2021-07-26
    • 2017-09-20
    相关资源
    最近更新 更多