【问题标题】:Using Angular Service in MEANJS 0.4.2在 MEANJS 0.4.2 中使用 Angular 服务
【发布时间】:2016-10-10 12:05:57
【问题描述】:

我有一个可能很简单的问题。我之前在 Angular 中使用过服务,但现在在使用 MEANJS Yeoman Generator 项目时遇到了问题。我需要做的是在另一个模块中使用来自特定模块的数组数据,这样我就可以在另一个模型的视图中重复这个。

我在服务中究竟在哪里引入数组?

(function () {
  'use strict';

  angular
  .module('patients')

  .factory('PatientsService', PatientsService);

  PatientsService.$inject = ['$resource'];

  function PatientsService($resource) {
    return $resource('api/patients/:patientId', {
      patientId: '@_id'
    }, {
      update: {
        method: 'PUT'
      }
    });
  }
})();

到目前为止,我在 MEANJS Doc 中一无所获,这里也没有(仅来自具有另一种服务结构的较旧 MEANJS 版本)。

这是我想在服务中带来的内容:

  // Shows a List of useable avatars on Patient creation
    $scope.avatars = [
      { value:'1', name: 'modules/patients/client/img/avatar/avatar1.png' },
      { value:'2', name: 'modules/patients/client/img/avatar/avatar2.png' },
      { value:'3', name: 'modules/patients/client/img/avatar/avatar3.png' },
      { value:'4', name: 'modules/patients/client/img/avatar/avatar4.png' },
      { value:'5', name: 'modules/patients/client/img/avatar/avatar5.png' },
      { value:'6', name: 'modules/patients/client/img/avatar/avatar6.png' }
    ];

我想在 home.client 视图中使用头像,并且 PatientService 已经注入到 home.client 控制器中。

【问题讨论】:

    标签: angularjs meanjs


    【解决方案1】:

    上面的服务只是返回一个$resource。相反,该服务可以返回具有各种属性的普通旧 Javascript 对象(或类)。其中有一个包含头像数组的属性,另一个包含$resource:

    (function () {
      'use strict';
    
      angular
      .module('patients')
    
      .factory('PatientsService', PatientsService);
    
      PatientsService.$inject = ['$resource'];
    
      function PatientsService($resource) {
        return {
          avatars: [ {value: 0, ... } ],
          resource: $resource('api/patients/:patientId', {
              patientId: '@_id'
            }, {
              update: {
                method: 'PUT'
            }
          })
        }
    
      }
    })();
    

    【讨论】:

    • 哦,我明白了,这确实很简单,但我尝试了完全错误的方式!非常感谢
    • 您知道我是否需要更改其他任何内容才能在整个应用程序中使用 $resources。好像不能用了?!
    • 自己搞定。我认为你可以同时使用它。 avatas 作为对象和资源,就像它们在对象之后一样。
    • return { avatars: [ { value:'1', ... } ] }, $resource('api/patients/:patientId', { patientId: '@_id' }, { update: { method: 'PUT' } });
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-09
    • 2017-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多