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

断了今生、忘了曾经 提交于 2019-12-13 20:54:13

问题


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


回答1:


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).




回答2:


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



来源:https://stackoverflow.com/questions/31046571/how-to-load-angular-formly-vm-fields-object-from-remotely-generated-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!