简体   繁体   中英

How to rewrite $resource factory as a class in ES6?

I'm rewriting all my AngularJs code in ES6. I have a User service that is a factory which returns the $resource object:

angular.module('cdcApp')
  .factory('User', function ($resource) {
    return $resource('/api/users/:id/:controller', {
      id: '@_id'
    },
    {
      changePassword: {
        method: 'PUT',
        params: {
          controller:'password'
        }
      },
      get: {
        method: 'GET',
        params: {
          id:'me'
        }
      }
    });
  });

It has been rewritten as the following:

class User {
  constructor($resource) {
    this.$resource = $resource;
    this.resource = this.$resource('/api/users/:id/:controller', {
      id: '@_id'
    }, {
      changePassword: {
        method: 'PUT',
        params: {
          controller: 'password'
        }
      },
      get: {
        method: 'GET',
        params: {
          id: 'me'
        }
      }
    });

  }
}
angular.module('cdcApp')
  .service('User', User);

However, it broke my old controller as I must use User.resource instead of just normal User as usual. Is there any workaround to achieve this?

try:

export default class Factory {
  constructor (API_ENDPOINT, $resource) {
    return $resource(API_ENDPOINT + "/url", {id: "@id"}, {
      update: {
        method: "PUT"
      }
    });
  }
  static activate(API_ENDPOINT, $resource) {
    Factory.instance = new Factory(API_ENDPOINT, $resource);
    return Factory.instance;
  }
}

Factory.$inject = ["API_ENDPOINT", "$resource"];

then in your module:

import Factory from "path_to_your_factory_file";
angular.module(name, [ngResource]).factory("Factory", Factory.activate);

Enjoy!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM