如何加载角formly vm.fields从远程生成的JSON对象? [英] How to load angular-formly vm.fields object from remotely-generated json?
问题描述
在我的应用我有什么,否则相同形式的动态字段设置。我可以从服务器加载它们,如JavaScript包括和工程确定。
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.
然而,这将是更好的,以便能够从一个单独的API加载它们。
However, it would be much better to be able to load them from a separate API.
$。的getJSON()提供加载JSON的好办法,但我还没有找到合适的地方来做到这一点。显然,它需要编译步骤开始之前完成。
$.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.
我看到有一个fieldTransform设施的formly。难道这是用来无论从API进来,从一个空对象变换vm.fields?
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。保罗
推荐答案
THX @kent
Thx @kent
好了,我们需要更换getFields()与此承诺
OK, so we need to replace the getFields() promise with this
function getFields() {
return $http.get('fields-demo.json', {headers:{'Cache-Control':'no-cache'}});
}
这所以vm.loadingData我们说返回data.fields
This returns data.fields so in vm.loadingData we say
vm.fields = result[0].data;
似乎就OK了为我工作。
Seems to work for OK for me.
在测试我注意到,你必须确保有什么不对您的JSON如使用还没有定义一个字段类型。在这种情况下所产生的错误信息不是很清楚。
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.
保
这篇关于如何加载角formly vm.fields从远程生成的JSON对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!