简体   繁体   English

AngularJS:处理各种json响应

[英]Angularjs : Handle varying json response

I am using API from a well known travel company and I am having this problem. 我正在使用知名旅游公司的API,但遇到了这个问题。

The problem is the response for roomAvailability . 问题是对roomAvailability的响应。

Now if certain hotel has only one Room Type , it sends it as a Room object rather than sending it as an array which otherwise it would send if there were multiple Room Types 现在,如果某些酒店只有一个“ Room Type ,则将其作为“ Room对象发送,而不是将其作为数组发送,否则,如果存在多个“ Room Types ,它将发送

Now in my template, I have a ng-repeat like : 现在在我的模板中,我有一个类似ng-repeat

<div ng-repeat='room in Rooms'>
Do some stuff like room.RoomType
</div>

Now what happens is , when Room is not an array , ng-repeat fails as it doesn't iterate over the Room array . 现在发生的是,当Room不是数组时, ng-repeat失败,因为它没有遍历Room array

Now what I can do is have a scope variable canIterate and repeat the code in my markup. 现在,我可以做的是有一个范围变量canIterate并在我的标记中重复代码。

But is there a better way so that I can avoid this repeat of code in markup ? 但是,是否有更好的方法可以避免在标记中重复代码?

Check HTTP response before putting it to $scope.Rooms. 将HTTP响应放入$ scope.Rooms之前,请先进行检查。 If response has field RoomType, declare $scope.Rooms = [response]; 如果响应的字段为RoomType,则声明$ scope.Rooms = [response]; otherwise $scope.Rooms = response; 否则$ scope.Rooms =响应;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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