如何将HTTP.call的结果传递给Meteor模板?
Alright, let's walk through fixing this step by step. The main hurdles in your current code are handling the this context correctly inside the HTTP callback and using a reactive data source so your template updates when the request completes. Here's what you need to do:
Step 1: Fix Context & Use ReactiveVar for User Data
First, update your onCreated function to preserve the template instance context and store the fetched users in a ReactiveVar—Meteor's reactive data type that triggers template updates when its value changes:
Template.hello.onCreated(function helloOnCreated() { // Counter starts at 0 this.counter = new ReactiveVar(0); // Save the template instance to avoid context loss in the async callback const templateInstance = this; // Initialize a ReactiveVar to hold users (starts as empty array) templateInstance.users = new ReactiveVar([]); const token = Meteor._localStorage.getItem("token"); // Check for token before making the request if (!token) { console.error("No authentication token found in localStorage"); return; } HTTP.call('GET', 'http://faa22147.ngrok.io/auth/users', { headers: { "Content-type": "application/json", 'Authorization': "Bearer " + token } }, function (error, result) { if (!error) { console.log("Fetched users:", result.data); // Update the ReactiveVar with the fetched data templateInstance.users.set(result.data); } else { console.error("Failed to fetch users:", error.response?.content || error.message); // Reset to empty array on error to keep template behavior consistent templateInstance.users.set([]); } }); });
Step 2: Add a Template Helper to Expose the Data
Templates can't directly access variables on the template instance, so you need a helper to retrieve the users ReactiveVar value:
Template.hello.helpers({ users() { // Get the current value from the ReactiveVar return Template.instance().users.get(); } });
Step 3: Render the Data in Your Template
Now you can loop through the users in your template using the helper. Adjust the fields to match your API's actual response structure:
<template name="hello"> <h1>User List</h1> {{#each user in users}} <div class="user-card"> <p>Name: {{user.name}}</p> <p>Email: {{user.email}}</p> </div> {{else}} <p>No users found, or loading...</p> {{/each}} </template>
Key Details to Remember:
- Context Preservation: By saving
thistotemplateInstance, we avoid losing access to the template instance inside the asynchronous HTTP callback (wherethiswould normally point to the global context, not the template). - Reactive Updates:
ReactiveVarensures that when we callset()with the fetched data, the template helper re-runs automatically, updating the UI with the new users. - Error Handling: We added checks for missing tokens and failed requests to keep the app predictable and log useful debugging information.
内容的提问来源于stack exchange,提问作者TDawg

