问题描述:

I am working with AngularJS 1.x on a web application which should be extended to provide a sort of API to customize some of its behavior by third-party developers. Obviously these developers cannot modify directly the source code of the application but must use the API I provide to extend it.

I provide you an example of the type of extension I want to provide with the API.

I have a page which displays a form. This form is dynamic and it is described by a JSON. There is an engine in the AngularJS page which read the JSON and render the form. There is also an AngularJS service, let's call it formService, which has the following methods:

  • getForm: using a REST API, get from the back-end the JSON describing the form structure to be rendered front-end side.
  • loadData: using a REST API, loads from the back-end the user data to be displayed.
  • saveData: using a REST API, saves into the back-end the data provided by the user in the form.

I need to provide an API that permits to third-party developers to customize this service. The third-party developer could:

  • load a different JSON to be displayed in the front-end. He/she can, for example, use a different REST call from the one I provide or build the JSON locally, inside the service.
  • load a different set of data to be displayed in the form. For example, his/her form could have different fields from the one I provide and so it could need other data.
  • save different set of data. Same as above.

My question is: how can I provide this kind of extensibility to the app?

The only option I found was to use the AngularJS decorator to let the third-party developer to decorate the formService and provide his/her own version of the methods. In this way the developer can extend or change implementation of specific methods or substitute the whole service implementation.

I made a lot of research and I think this is the best "angular style" solution to extend an existing service from a third party.

Do you know any other good solution to enable third-party developers to customize the behavior of an existing service?

网友答案:

Actually your question is too broad and I dont think your idea is so good in general, but nvm. You can use $injector:

.directive('strangeForm', ...
    link : function() {
      formCfg = $injector.get(attrs.formService).get();
      data = $injector.get(attrs.dataService).get();
      onSave = $injector.get(attrs.saveService).onSave;
    }

<form strange-form form-service="service1" data-service="service2" save-service="service3"
相关阅读:
Top