【问题标题】:AngularJS: objects, arrays, JSON, API issuesAngularJS:对象、数组、JSON、API 问题
【发布时间】:2015-07-27 13:34:24
【问题描述】:

创建:

我正在使用$scope.services 来存储我的服务列表。这是一个对象数组:

$scope.services = [{
    title           : undefined,
    quantity        : undefined,
    pricePerUnit    : undefined,
    priceCalculated : undefined,
    order           : undefined         
}];

然后我可以将另一个对象推入数组。

$scope.services.push({ 
    title           : undefined,
    quantity        : undefined,
    pricePerUnit    : undefined,
    priceCalculated : undefined,
    order           : undefined
});

到目前为止,一切都很好。然后我在 Angular 中使用这个对象作为模型来显示它的内容。

更新:

我正在调用 API 并获取我的 JSON 格式:

{
    someData: "some data",
    services: {
        0: {
            id: 101,
            offer_id: 101,
            title: "some title",
            ...
        },
        1: {
            ...
        }
    }
}

通过$scope.services = data.services 附加接收到的数据,然后当我调用$scope.services.push 时出现控制台错误

TypeError: $scope.services.push is not a function.

可能出了什么问题?是 JSON/数组问题吗?我从来没有深入了解这一点,所以任何理论知识也将不胜感激。提前谢谢你。

【问题讨论】:

  • 为什么要创建数组,然后在收到不是数组的数据时将其清除?在新数据中使用索引键作为对象属性也没有任何意义。需要微调您的数据源输出并使服务属性成为数组而不是对象

标签: javascript json angularjs object


【解决方案1】:

因为 services 不是数组,(push 是为数组定义的:Array.prototype.push())你需要从响应中构造一个合适的数组。

var servicesArray = [];
Object.keys(data.services).forEach(function (key) {
   servicesArray.push(data.services[key]);
}); 
$scope.services = servicesArray;

【讨论】:

【解决方案2】:

我认为您分配的对象(data.services)$scope.services = data.services 可能不是数组。交叉检查来自data.services 的对象是否是数组。发现了一个类似的问题 (link),可能对您有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-05
    • 2016-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-10
    相关资源
    最近更新 更多