如何将 http.call 结果传递给模板?

How to pass http.call results to a template?

我的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>

reactive computation is invalidated.

时,模板助手被重新 运行

A 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 助手无效(设置为数组)时,它重新 运行s,并且 users 现在是真实的,并且内部 each 被触发。

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

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