3

我想做什么? 我正在尝试通过开发一个简单的 Web 应用程序来学习 Javascript 和 MEAN 堆栈。在该应用程序中,我尝试在 Web 应用程序中使用 angular-smart-table 的“管道/ajax 插件”,其规格如下:客户端:AngularJS 服务器端:ExpressJS/NodeJS(使用 Yeoman 生成器“生成器创建” -角全栈“)

我面临的挑战:我在我的 Web 应用程序 的智能表文档中复制/粘贴了管道/ajax 插件示例。此示例具有要在客户端(工厂)的智能表中显示的值。我想将这些值移动到可通过 REST API 端点 $http.get('/api/smartTableServer') 访问的服务器控制器文件(plunker 中的 smartTableServer.controller.js)。

到目前为止,我在这方面取得了什么成就? 我能够成功地将服务器控制器文件中的数据读取到客户端工厂文件(smartTableClient.service.js)中。但是,当我将它存储在一个变量(randomsItems)中时,该变量的值是“未定义的”。我相信 http get 调用是稍后执行的,因此变量 randomsItems 仍然没有从服务器获取值。你能帮我解决这个问题吗?(ie) 从服务器控制器 JS 中获取 randomsItems 的值并将其显示在视图中。

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

请注意: 我仍然不知道异步脚本是如何工作的,因此不知道延迟和承诺概念,我认为这是我面临上述问题的原因。我还在学习基础知识。请帮助。

4

1 回答 1

3

function getRandomItems()必须采用必须在以下方法内部调用的success回调$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 
  };
)

或者promisefunction getRandomItems()and 中返回一个:

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 一般用法

于 2015-07-22T20:20:02.870 回答