使用服务与Angular和Mean.js在控制器之间共享数据

时间:2015-07-24 20:17:49

标签: angularjs mean meanjs

好的我几天前问过这个没有开始编码的问题。现在经过一些研究并玩弄代码后,我发现自己有点失落。

我会更好地解释自己并分享我迄今为止所做的代码。我仍然是一个Angular“noob”,所以我希望你们能帮助我做到这一点。

我正在使用Mean.js开发一个应用程序,它在客户端使用Angular。 Mean.js在不同的目录中分别创建模块,每个模块都有服务器和客户端目录。到目前为止,我创建了一个Customers模块和一个Appointments模块(这些模块就像CRUD模块一样)

创建约会时,我希望能够从客户列表中选择客户(这意味着我必须从客户控制器获取该数据)

在创建约会视图中,我有这个typeahead组件,我想在输入客户名字时显示客户:

<section data-ng-controller="AppointmentsController">
    <input type="text" ng-model="asyncSelected" typeahead="customer for customer in findCust()" typeahead-loading="loadingCustomers" class="form-control">
</section>

与此同时,在Customers模块中,我创建了一个服务(这是我仍然不太了解的一件事)使用yeoman服务生成器为mean.js,这基本上是一个模板,我只是添加了一些类似于Customers.query()的调用,它是客户客户端控制器中的一个功能,调用服务器控制器以使客户列表更具体:

'use strict';

angular.module('customers').factory('ShareService', [ 'Customers',
  function(Customers) {
    // Share service logic
    // ...

    // Public API
    return {
        listCustomers: function() {
            Customers.query(); //I added this call 
        }
    };
  }
]);

然后我将以下代码行添加到Appointments控制器中,希望开始让这个东西起作用:

'use strict';

// Appointments controller
angular.module('appointments').controller('AppointmentsController',['$scope', '$stateParams', '$location', 
 'Authentication', 'Appointments','ShareService',
    function($scope, $stateParams, $location, Authentication, Appointments, ShareService) {
        $scope.authentication = Authentication;

        /* 
            Appointments CRUD ops logic here
        */

        // Find a list of Customers
        $scope.findCust = function() {
            ShareService.listCustomers();
        };
    }
]);

之后我去了应用程序,但没有数据被发送,控制台在输入文本框时给我这个错误:

Cannot read property 'length' of undefined

所以当然没有达到我的预期。我知道我可能在这里遇到一些重大错误。事实证明,Angular在某些方面很容易,但在其他方面很复杂(至少对我而言),模块/控制器之间的这种通信让我陷入困境。

为了澄清,我在两个单独的目录(客户和约会)中有两个模块,我将ShareService添加到客户模块(因此我能够“共享”一些信息)。我到目前为止唯一的错误是浏览器控制台给出的错误。在grunt控制台中没有错误。但这有点乱,所以我知道我做错了。什么?这就是问题所在。

感谢您的时间。

1 个答案:

答案 0 :(得分:1)

嗯,您正在调用listCustomers ShareService,但此服务没有使用此名称的方法。

刚刚将ShareService的返回对象更改为:

return {
    listCustomers: function() {
        Customers.query(); //I added this call
    }
};

修改

listCutomers函数没有返回任何内容,这就是未定义对象的原因。只需添加如下所示的回报:

return {
    listCustomers: function() {
        return Customers.query(); //I added this call
    }
};