【问题标题】:Unable to fetch list of files from back-end to front-end angular select options?无法从后端获取文件列表到前端角度选择选项?
【发布时间】:2017-02-13 12:39:31
【问题描述】:

我正在使用node.jsserver.js 文件中的目录('.public/jsonfiles')获取文件。但是我无法使用AngularJSNode.js 服务将这些文件列表显示在我的视图页面上。

错误:

我收到 data.forEach 不是函数错误(我可以在控制台中看到全部 html 内容,而不是在返回语句中的服务文件中看到我的文件列表:return $http.get('/public/jsonfiles');

否则,如果我给出:return $http.get('').then(function(data){ console.log(data)}); /giving Main.get() 成功不是一个函数,总共给出html content on console

创建repository

【问题讨论】:

    标签: javascript angularjs json node.js express


    【解决方案1】:

    我看了你的回购。应要求

     return $http.get('/public/jsonfiles');
    

    node 将返回 index.html,这将使 data.forEach 上出现 MainCtrl 错误,因为 data 不是数组。

    如果您安装 serve-index 并使用它为 public 提供目录列表,它应该可以工作。

    var serveIndex = require('serve-index');
    app.use('/public',serveIndex('public'));
    

    (server.js)

    要加载文件 json,请向 MainService 添加另一个方法来获取文件。

        getFile: function (filename) {
            //no public in the path because node is removing when it serves static files
            return $http.get('/jsonfiles/' + filename);
        }
    

    在 MainCtrl 中,您可以在所选文件更改时加载文件内容。

      $scope.optionChanged = function () {
         Main.getFile( $scope.selectedjsoncontent )
             .success(function(result){
               $scope.textAreaData = result;
             });    
    

    }

    【讨论】:

    • 感谢您的回复,我已经安装了serve-index并在server.js中添加了上面两行代码,但是我得到同样的错误,我希望我需要重新配置还是需要在 server.js 中正确添加/生成任何内容?请让我知道,我已经更新了我的回购:github.com/mavarma/GetListofFiles
    • @Dhana 你可以试试 app.use('/public/jsonfiles',serveIndex('public/jsonfiles/'));。这对我有用。
    • 是的,它现在工作正常,根据你的说法,但它给出了文件名,我的意思是我需要它们各自选择的选项数据(我需要在我的文本区域中获取 json 数据而不是它们的文件名)
    • 我需要在 textarea 中显示我选择的选项的 json 内容,而不是显示 json 文件名。
    • @Dhana 当所选选项更改以获取内容并将结果加载到控制器上的属性中时,您将不得不使用文件名执行另一个获取请求。然后,您可以将该属性绑定到文本区域。
    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 2022-07-27
    • 2023-03-26
    • 2015-01-23
    • 1970-01-01
    • 2019-08-02
    • 1970-01-01
    • 2020-06-14
    相关资源
    最近更新 更多