How to load angular-formly vm.fields object from remotely-generated json?

2.6k views Asked by At

In my application I have dynamic field sets on what is otherwise the same form. I can load them from the server as javascript includes and that works OK.

However, it would be much better to be able to load them from a separate API.

$.getJSON() provides a good way to load the json but I have not found the right place to do this. Clearly it needs to be completed before the compile step begins.

I see there is a fieldTransform facility in formly. Could this be used to transform vm.fields from an empty object to whatever comes in from the API?

If so how would I do that?

Thx. Paul

2

There are 2 answers

2
kentcdodds On

There is an example on the website that does exactly what you're asking about. It uses $timeout to simulate an async operation to load the field configuration, but you could just as easily use angular's own $http to get the json from the server. It hides the form behind an ng-if and only shows the form when the fields return (when ng-if resolves to true, it compile the template).

1
user1712240 On

Thx @kent

OK, so we need to replace the getFields() promise with this

function getFields() {
  return $http.get('fields-demo.json', {headers:{'Cache-Control':'no-cache'}});
}       

This returns data.fields so in vm.loadingData we say

vm.fields = result[0].data;

Seems to work for OK for me.

When testing I noticed that you have to make sure there is nothing wrong with your json such as using a field type you haven't defined. In that case the resulting error message is not very clear.

Furthermore you need to deal with the situation where the source of the data is unavailable. I tried this:

function getFields() {
  console.log('getting',fields_url);
    return $http.get(fields_url, {headers: {'Cache-Control':'no-cache'}}).
    error(function() {
      alert("can't get fields from server");
      //return new Promise({status:'fields server access error'}); //??
    });

.. which does at least throw the alert. However, I'm not sure how to replace the promise so as to propagate the error back to the caller.

Paul