javascript - 无法将 fs.readFile 数据分配给工厂对象属性

标签 javascript angularjs node.js

我正在尝试在 Angularjs 服务中调用 fs.readFile,该服务是一个包含方法和属性的对象。

我从服务对象的方法中调用 fs.readFile,并尝试将读取的数据分配给服务对象的属性,但这总是导致未定义。下面的代码应该可以清楚地表达我的意图;

    angular.module('myApp.controllers', []).controller('exampleCtrl', function(objectFac){
        objectFac.func();
        console.log(objectFac.prop); // Undefined
        console.log(objectFac.object.prop); // Undefined
    });

   angular.module('myApp.Services').service('objectFac', function (){
        this.prop = '';
        this.object.prop = '';
        this.func = function(){
            this.param = fs.readFileSync(filePath, 'utf-8'); //If I use a call back (non Sync) and log the data to console, it shows correctly but I cannot assign it to objectFac.prop or object.prop. 
    };

我尝试了 readFile 和 readFileSync,两者都出现同样的情况。我能够将从文件中检索到的数据记录到控制台,只是不分配给我想要的对象属性。它总是导致未定义。

谢谢。

最佳答案

服务是使用 Angular 中的new 关键字创建的,因此为了解决您的问题,请执行以下操作:

angular.module('myApp.Services').service('objectFac', function() {
          this.prop = '';
          this.object.prop = '';
          this.func = function() {
            this.param = fs.readFileSync(filePath, 'utf-8');
}

变成:

angular.module('myApp.Services').service('objectFac', function() {
      return function() {
          this.prop = '';
          this.object.prop = '';
          this.func = function() {
            this.param = fs.readFileSync(filePath, 'utf-8');
          }
}

关于javascript - 无法将 fs.readFile 数据分配给工厂对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34494239/

相关文章:

javascript - Uncaught ReferenceError : *function here* is not defined

javascript - 无法使用 Bootstrap 查看响应式 Angular NVD3 图表

javascript - 由于 "too much recursion", Angular 等于方法失败

java - node.js 准备好替换服务器任务了吗?

javascript - 我怎样才能为所有模态制作一个脚本?

javascript - jPlayer 进度条旋钮

javascript - 使用 JS 对象查询 MySQL,返回 [object Object] 作为表名

javascript - 使用 Node.js 全局连接 Sql 查询

javascript - 如何对数组中的最后一个对象进行异常(exception)处理?

javascript - Angularjs 问题 $http.get 未加载图像