我想做什么? 我正在尝试通过开发一个简单的 Web 应用程序来学习 Javascript 和 MEAN 堆栈。在该应用程序中,我尝试在具有以下规范的 Web 应用程序中使用 angular-smart-table 的“pipe/ajax 插件”: 客户端:AngularJS 服务器端:ExpressJS/NodeJS (使用 Yeoman 生成器“generator-angular-fullstack”创建)
我面临的挑战: 我复制/粘贴了智能表中给出的管道/ajax 插件示例 documentation在我的网络应用程序中。此示例具有要在客户端(工厂)的智能表中显示的值。我想将这些值移动到可通过 REST API 端点 $http.get('/api/smartTableServer') 访问的服务器 Controller 文件(plunker 中的 smartTableServer.controller.js)。
到目前为止,我在这方面取得了什么成就? 我能够成功地将服务器 Controller 文件中的数据读取到客户端工厂文件 (smartTableClient.service.js) 中。但是,当我将它存储在变量 (randomsItems) 中时,变量的值为“未定义”。我相信 http get 调用稍后执行,因此变量 randomsItems 仍然没有从服务器获取值。你能帮我解决这个问题吗? (即)从服务器 Controller JS 获取 randomsItems 的值并将其显示在 View 中。
我的与此问题相关的文件的 Plunker:
`angular.module('myApp').factory('Resource', ['$q', '$filter', '$timeout', '$http', function ($q, $filter, $timeout, $http) {
//this would be the service to call your server, a standard bridge between your model an $http
// the database (normally on your server)
function getrandomsItems() {
var defer = $q.defer();
$http.get('/api/smartTableServer', { cache: 'true'}).success(
function(randomsItems) {
defer.resolve(randomsItems);
//randomsItems = angular.fromJson(randomsItems);
//console.log("Success - randomsItems : " + randomsItems);
//console.log("Success - randomsItems.Stringify : " + JSON.stringify(randomsItems));
return defer.promise;
}
);
return defer.promise;
}
function getPage(start, number, params) {
var randomsItems = getrandomsItems(); // This method call returns the value as undefined!!!
... `
http://plnkr.co/edit/jRdNXuVMrWaymLnxfPnE?p=catalogue
请注意: 我仍然不知道异步脚本是如何工作的,因此不知道延迟和 promise 的概念,我认为这是我面临上述问题的原因。我仍在学习基础知识。请帮忙。
最佳答案
function getRandomItems()
必须接受回调,该回调必须在 $http.get('/api/smartTableServer', { cache : 'true'})
promise
:
function getRandomItems(cb) {
$http.get('/api/smartTableServer', {cache: 'true'})
.success(function(randomItems) { cb(randomItems); });
}
function getPage(start, number, params) {
getRandomItems(function cb(randomItems) {
// do what you want to do with randomItems
};
)
或者从 function getRandomItems()
返回一个 promise
和:
function getRandomItems(cb) {
return $http.get('/api/smartTableServer', {cache: 'true'});
}
function getPage(start, number, params) {
getRandomItems.success(function(randomItems) {
// do what you want to do with randomItems
};
)
更多文档在这里:$http General usage
关于javascript - 从 ExpressJS 服务器读取数据以显示在 angular-smart-table 的 pipe/ajax 插件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31572979/